在 pandas 数据框中识别组中重复项的更好方法? [英] Better way to identify duplicates in a group in a Pandas dataframe?
本文介绍了在 pandas 数据框中识别组中重复项的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框
x c
0 0 1
1 3 2
2 1 1
3 2 1
4 3 1
5 4 1
6 1 0
7 3 1
8 2 1
9 1 2
我想生产
c x duplicated
0 1 0 False
1 2 3 False
2 1 1 False
3 1 2 True
4 1 3 True
5 1 4 False
6 0 1 False
7 1 3 True
8 1 2 True
9 2 1 False
即先按 c
分组,然后标记该组中所有重复的行
that is to group by c
first, and mark all duplicated rows in the group.
我目前的做法是
c = np.random.randint(0, 3, 10)
x = np.random.randint(0, 5, 10)
d = pd.DataFrame({'x': x, 'c': c})
d['duplicated'] = d.groupby('c').apply(
lambda x: x.duplicated(keep=False)
).reset_index(level=0, drop=True)
是否有ny更好的方法?
Is there any better way?
推荐答案
使用仅重复
-默认情况下,它会验证所有列:
Use duplicated
only - by default it verify all columns:
d['duplicated'] = d.duplicated(keep=False)
print (d)
x c duplicated
0 0 1 False
1 3 2 False
2 1 1 False
3 2 1 True
4 3 1 True
5 4 1 False
6 1 0 False
7 3 1 True
8 2 1 True
9 1 2 False
d['duplicated'] = d.duplicated(subset=['c','x'],keep=False)
print (d)
x c duplicated
0 0 1 False
1 3 2 False
2 1 1 False
3 2 1 True
4 3 1 True
5 4 1 False
6 1 0 False
7 3 1 True
8 2 1 True
9 1 2 False
这篇关于在 pandas 数据框中识别组中重复项的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文