如何获取 Dataframe 的删除副本索引

bqujaahr  于 2021-08-25  发布在  Java
关注(0)|答案(2)|浏览(435)

我正在使用 df = df.drop_duplicates(["col1",["col2"]) 在我的pandas Dataframe 上,但我需要知道删除的行索引,我如何才能做到这一点?

50pmv0ei

50pmv0ei1#

使用 boolean indexing 戴着面具 DataFrame.duplicated 仅适用于指数:

  1. df = pd.DataFrame({'col1':[1] * 4, 'col2':[2,2,3,2]})
  2. print (df)
  3. col1 col2
  4. 0 1 2
  5. 1 1 2
  6. 2 1 3
  7. 3 1 2
  8. print (df.drop_duplicates(["col1","col2"]))
  9. col1 col2
  10. 0 1 2
  11. 2 1 3
  1. mask = df.duplicated(["col1","col2"])
  2. idx = df.index[mask]
  3. print (idx)
  4. Int64Index([1, 3], dtype='int64')

或使用 Index.difference 如果已删除重复项:

  1. df1 = df.drop_duplicates(["col1","col2"])
  2. idx = df.index.difference(df1.index)
  3. print (idx)
  4. Int64Index([1, 3], dtype='int64')
展开查看全部
efzxgjgh

efzxgjgh2#

你可以去 duplicated :

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

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

相关问题