pandas 标签重复项 [英] Pandas Label Duplicates
本文介绍了 pandas 标签重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下数据框:
import pandas as pd
d=pd.DataFrame({'label':[1,2,2,2,3,4,4],
'values':[3,5,7,2,5,8,3]})
d
label values
0 1 3
1 2 5
2 2 7
3 2 2
4 3 5
5 4 8
6 4 3
我知道如何计算像这样的唯一值:
I know how to count the unique values like this:
d['dup']=d.groupby('label')['label'].transform('count')
这将导致:
label values dup
0 1 3 1
1 2 5 3
2 2 7 3
3 2 2 3
4 3 5 1
5 4 8 2
6 4 3 2
但是我想让一列具有以下值:
如果每个标签列有1 unique
行,则为1
;如果存在duplicates
,并且该行为该行的first
,则为2
;如果该行是duplicate
的行,则为0
原件.像这样:
But what I would like is a column to have the following values:
1
if there is 1 unique
row per the label column, 2
if there are duplicates
and the row in question is the first
of such, and 0
if the row is a duplicate
of an original. Like this:
label values dup status
0 1 3 1 1
1 2 5 3 2
2 2 7 3 0
3 2 2 3 0
4 3 5 1 1
5 4 8 2 2
6 4 3 2 0
提前谢谢!
推荐答案
我认为您可以使用 duplicated
:
I think you can use loc
with condition created by function duplicated
:
d['status'] = 2
d.loc[d.dup == 1, 'status'] = 1
d.loc[d.label.duplicated(), 'status'] = 0
print (d)
label values dup status
0 1 3 1 1
1 2 5 3 2
2 2 7 3 0
3 2 2 3 0
4 3 5 1 1
5 4 8 2 2
6 4 3 2 0
或加倍 numpy.where
:
d['status1'] = np.where(d.dup == 1, 1,
np.where(d.label.duplicated(), 0, 2))
print (d)
label values dup status status1
0 1 3 1 1 1
1 2 5 3 2 2
2 2 7 3 0 0
3 2 2 3 0 0
4 3 5 1 1 1
5 4 8 2 2 2
6 4 3 2 0 0
这篇关于 pandas 标签重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文