【问题标题】:Pandas drop duplicates only for main indexPandas 仅删除主索引的重复项
【发布时间】:2022-11-21 21:12:06
【问题描述】:

我有一个多索引,我想在每个级别的基础上执行 drop_duplicates,我不想查看整个数据框,但前提是存在具有相同主索引的重复项

例子:

entry,subentry,A,B

1 0 1.0 1.0
  1 1.0 1.0
  2 2.0 2.0

2 0 1.0 1.0
  1 2.0 2.0
  2 2.0 2.0

应该返回:

entry,subentry,A,B

1 0 1.0 1.0
  1 2.0 2.0

2 0 1.0 1.0
  1 2.0 2.0

【问题讨论】:

    标签: pandas


    【解决方案1】:

    使用 MultiIndex.get_level_valuesIndex.duplicated 过滤掉每个 entry 的最后一行:

    df1 = df[df.index.get_level_values('entry').duplicated(keep='last')]
    print (df1)
    
                      A    B
    entry subentry          
    1     0         1.0  1.0
          1         1.0  1.0
    2     0         1.0  1.0
          1         2.0  2.0
    

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 2012-10-13
      • 2021-10-02
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      相关资源
      最近更新 更多