我有一个数据帧:
>>> df
A
0 foo
1 bar
2 foo
3 baz
4 foo
5 bar
我需要找到所有重复的组并用顺序的dgroup_id
标记它们:
(这意味着foo
属于第一组重复项,bar
属于第二组重复项,baz
不重复。)
我这样做了:
import pandas as pd
df = pd.DataFrame({'A': ('foo', 'bar', 'foo', 'baz', 'foo', 'bar')})
duplicates = df.groupby('A').size()
duplicates = duplicates[duplicates>1]
# Yes, this is ugly, but I didn't know how to do it otherwise:
duplicates[duplicates.reset_index().index] = duplicates.reset_index().index
df.insert(1, 'dgroup_id', df['A'].map(duplicates))
这导致:
>>> df
A dgroup_id
0 foo 1.0
1 bar 0.0
2 foo 1.0
3 baz NaN
4 foo 1.0
5 bar 0.0
在大熊猫身上有没有更简单/更短的方法来实现这一点?我读到pandas.factorize
可能对这里有帮助,但我不知道如何使用它。。。(此函数上的pandas documentation没有帮助)
另外:我不介意基于0的组计数,也不介意奇怪的排序顺序;但是我希望dgroup_id
作为int,而不是float。在
您可以通过
get_duplicates()
创建一个list
副本,然后通过A
的索引设置dgroup_id
输出:
^{pr2}$你可以选择:
使用链式运算首先得到每个A的值_count,计算每个组的序号,然后连接回原始DF。在
如果您需要唯一组的Nan,就不能使用int作为数据类型,这是目前pandas的一个限制。如果对唯一组设置0没有问题,可以执行以下操作:
^{pr2}$相关问题 更多 >
编程相关推荐