gpt4 book ai didi

python - 为 Pandas 中的列添加具有重复值的数字

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:24 25 4
gpt4 key购买 nike

我有一个这样的数据框:

df:
col1 col2
1 pqr
3 abc
2 pqr
4 xyz
1 pqr

我发现有重复的值和它的pqr。我想在出现 pqr 的地方添加 1,2,3。我要实现的最终数据框是:

df1
col1 col2
1 pqr1
3 abc
2 pqr2
4 xyz
1 pqr3

如何高效地做到这一点

最佳答案

使用duplicated对所有重复行使用 keep=False 并添加由 cumcount 创建的计数器:

mask = df['col2'].duplicated(keep=False)
df.loc[mask, 'col2'] += df.groupby('col2').cumcount().add(1).astype(str)

或者:

df['col2'] = np.where(df['col2'].duplicated(keep=False), 
df['col2'] + df.groupby('col2').cumcount().add(1).astype(str),
df['col2'])
print (df)
col1 col2
0 1 pqr1
1 3 abc
2 2 pqr2
3 4 xyz
4 1 pqr3

如果只需要相同的pqr 值:

mask = df['col2'] == 'pqr'
df.loc[mask, 'col2'] += pd.Series(np.arange(1, mask.sum() + 1),
index=df.index[mask]).astype(str)
print (df)
col1 col2
0 1 pqr1
1 3 abc
2 2 pqr2
3 4 xyz
4 1 pqr3

关于python - 为 Pandas 中的列添加具有重复值的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54105419/

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