gpt4 book ai didi

python - 使用 Pandas/Python 为列中的重复项生成唯一值

转载 作者:行者123 更新时间:2023-12-04 02:28:58 25 4
gpt4 key购买 nike

我有一个数据集 df,我想通过在末尾放置数字来为类型列中的值创建唯一 ID。

数据

type    total   free  use
a 10 5 5
a 10 4 6
a 10 1 9
a 10 8 2
a 10 3 7
b 20 5 5
b 20 3 7
b 20 2 8
b 20 6 4
b 20 2 8

想要的

type    total   free  use
a 10 5 5
a1 10 4 6
a2 10 1 9
a3 10 8 2
a4 10 3 7
b 20 5 5
b1 20 3 7
b2 20 2 8
b3 20 6 4
b4 20 2 8

我可以通过这样做在 R 中做到这一点,但不确定如何在 Python 中做到这一点:

library(data.table)
setDT(DT)

DT[ , run_id := rleid(ID)]
DT[DT[ , .SD[1L], by = run_id][duplicated(ID), ID := paste0('list', .I)],
on = 'run_id', ID := i.ID][]

我正在研究这个,欢迎任何意见

最佳答案

您可以使用groupby.cumcount:

df['type'] += np.where(df['type'].duplicated(),
df.groupby('type').cumcount().astype(str),
'')

或者类似地使用 loc 更新:

df.loc[df['type'].duplicated(), 'type'] += df.groupby('type').cumcount().astype(str)

输出:

  type  total  free  use
0 a 10 5 5
1 a1 10 4 6
2 a2 10 1 9
3 a3 10 8 2
4 a4 10 3 7
5 b 20 5 5
6 b1 20 3 7
7 b2 20 2 8
8 b3 20 6 4
9 b4 20 2 8

关于python - 使用 Pandas/Python 为列中的重复项生成唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65500785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com