我有一个包含重复行的 DataFrame,我希望得到一个唯一索引且无重复的 DataFrame。可以丢弃重复值。这个操作可以通过 groupby
实现吗?
In [29]: df.drop_duplicates()
Out[29]:
b c
1 2 3
3 4 0
7 5 9
通过阅读split-apply-combine文档示例,找到了一种方法来实现它。
df = pandas.DataFrame({'b':[2,2,4,5], 'c': [3,3,0,9]}, index=[1,1,3,7])
df_unique = df.groupby(level=0).first()
df
b c
1 2 3
1 2 3
3 4 0
7 5 9
df_unique
b c
1 2 3
3 4 0
7 5 9
unstack
时,出现了ValueError: Index contains duplicate entries, cannot reshape
的错误,但是这个解决方案对此有效,只需要执行df_unique = df.groupby(level=[0,1]).first()
即可。 - dashesy
df.drop_duplicates(inplace=True)
。 - Flavian Hautbois