我有一个数据集 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
Run Code Online (Sandbox Code Playgroud)
想要的
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
Run Code Online (Sandbox Code Playgroud)
正在做
我能够通过这样做在 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][]
Run Code Online (Sandbox Code Playgroud)
我正在研究这个,任何输入表示赞赏
您可以使用groupby.cumcount:
df['type'] += np.where(df['type'].duplicated(),
df.groupby('type').cumcount().astype(str),
'')
Run Code Online (Sandbox Code Playgroud)
或类似的loc更新:
df.loc[df['type'].duplicated(), 'type'] += df.groupby('type').cumcount().astype(str)
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)