Pandas DataFrame的drop_duplicates
方法在删除重复行时会考虑所有列(默认)或列子集(可选),并且不能考虑重复索引。
我正在寻找一种干净的单行解决方案,该方案在确定重复行时考虑索引和子集或所有列。例如,考虑DataFrame
df = pd.DataFrame(index=['a', 'b', 'b', 'c'], data={'A': [0, 0, 0, 0], 'B': [1, 0, 0, 0]})
A B
a 0 1
b 0 0
b 0 0
c 0 0
默认使用
drop_duplicates
方法可以df.drop_duplicates()
A B
a 0 1
b 0 0
如果在确定重复行时也考虑了索引,则结果应为
df.drop_duplicates(consider_index=True) # not a supported keyword argument
A B
a 0 1
b 0 0
c 0 0
有没有一种方法可以提供此功能,这比我目前的方法要好:
df['index'] = df.index
df.drop_duplicates(inplace=True)
del df['index']
最佳答案
调用reset_index
和duplicated
,然后为原始索引:
df = df[~df.reset_index().duplicated().values]
print (df)
A B
a 0 1
b 0 0
c 0 0
关于python - 在pandas DataFrame的drop_duplicates方法中考虑重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52105181/