Python 在列组合中查找重复项
我需要在两列中保留唯一的记录。 想象一下,在下面的数据帧(df)中,我想删除x列和y列中的重复信息 x y z 1 3 1 4 4 3 2 4 3 1 3 2 352 我所做的是连接XY=str(x)+str(y),并通过pd.unique(df.XY())保持唯一值。 记录(1 3 1)和(1 3 2)将是重复的 我相信一定有更好的方法来做到这一点。。。尤其是涉及到3列或更多列时。 谢谢 MB使用: 您可以使用参数Python 在列组合中查找重复项,python,pandas,duplicates,Python,Pandas,Duplicates,我需要在两列中保留唯一的记录。 想象一下,在下面的数据帧(df)中,我想删除x列和y列中的重复信息 x y z 1 3 1 4 4 3 2 4 3 1 3 2 352 我所做的是连接XY=str(x)+str(y),并通过pd.unique(df.XY())保持唯一值。 记录(1 3 1)和(1 3 2)将是重复的 我相信一定有更好的方法来做到这一点。。。尤其是涉及到3列或更多列时。 谢谢 MB使用: 您可以使用参数keep保留first或last重复行: print df.drop_dupli
keep
保留first
或last
重复行:
print df.drop_duplicates(subset=['x','y'])
#it is same as:
print df.drop_duplicates(subset=['x','y'], keep='first')
x y z
0 1 3 1
1 4 4 3
2 2 4 3
4 3 5 2
print df.drop_duplicates(subset=['x','y'], keep='last')
x y z
1 4 4 3
2 2 4 3
3 1 3 2
4 3 5 2
如果需要删除所有重复项,请使用keep=False
:
print df.drop_duplicates(subset=['x','y'], keep=False)
x y z
1 4 4 3
2 2 4 3
4 3 5 2
df.drop_duplicates(subset=['x','y'])
应该可以工作,您想保留第一个副本还是删除它?如果是后者,那么您需要将keep=False
作为一个附加参数,这里有很多相关的问题:谢谢,我被单列副本淹没了。。。我在浏览问题时遇到了措辞上的问题。。。
print df.drop_duplicates(subset=['x','y'], keep=False)
x y z
1 4 4 3
2 2 4 3
4 3 5 2