为 pandas 中的列添加具有重复值的数字 [英] Add numbers with duplicate values for columns in pandas

查看:96
本文介绍了为 pandas 中的列添加具有重复值的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a data frame like this:

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

我发现有重复的值及其pqr.我想在发生pqr的地方添加1,2,3.我要实现的最终数据帧是:

I found that there is duplicate value and its pqr. I want to add 1,2,3 where pqr occurs. The final data frame I want to achieve is:

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

如何高效地做到这一点

推荐答案

使用 duplicated keep=False用于所有重复行,并添加由

Use duplicated with keep=False for all dupe rows and add counter created by 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值需要相同的内容:

If need same only for pqr values:

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

这篇关于为 pandas 中的列添加具有重复值的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆