如何删除熊猫数据框的重复索引

时间:2021-07-08 13:30:43

标签: python python-3.x pandas dataframe indexing

我在我的 Pandas 数据帧上使用了 df = df.drop_duplicates(["col1",["col2"]),但我需要知道删除的行索引,我该怎么做?

2 个答案:

答案 0 :(得分:2)

仅将 boolean indexingDataFrame.duplicated 的掩码用于索引:

df = pd.DataFrame({'col1':[1] * 4, 'col2':[2,2,3,2]})
print (df)
   col1  col2
0     1     2
1     1     2
2     1     3
3     1     2
    
print (df.drop_duplicates(["col1","col2"]))
   col1  col2
0     1     2
2     1     3

mask = df.duplicated(["col1","col2"])
idx = df.index[mask]
print (idx)
Int64Index([1, 3], dtype='int64')

如果已删除重复项,则使用 Index.difference

df1 = df.drop_duplicates(["col1","col2"])
idx = df.index.difference(df1.index)
print (idx)
Int64Index([1, 3], dtype='int64')

答案 1 :(得分:1)

你可以选择duplicated

dups = df.duplicated(["col1", "col2"])
dups[dups].index

第一行给出一个布尔数组,用于标记一行是否重复。第二行使用布尔索引来选择 True 条目,我们得到它们的索引。