我有一个像这样的数据框:
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
如何高效地做到这一点
Use duplicated http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.duplicated.html with keep=False
对于所有重复行并添加由创建的计数器cumcount http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html:
mask = df['col2'].duplicated(keep=False)
df.loc[mask, 'col2'] += df.groupby('col2').cumcount().add(1).astype(str)
Or:
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
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)