【问题标题】:Get special group in pandas multiindex在熊猫多索引中获取特殊组
【发布时间】:2018-06-13 21:44:49
【问题描述】:

我有一个带有 MultiIndex 的 DataFrame,如下所示:

In [5]: df
Out[5]:
                 a   b
lvl0 lvl1 lvl2
A0   B0   C0     0   1
          C1     2   3
          C2     4   5
          C3     6   7
     B1   C0     8   9
          C1    10  11
          C2    12  13
          C3    14  15
A1   B0   C0    16  47
          C1    18  49
          C2    20  41
          C3    22  43
     B1   C0    24  25
          C1    26  27
          C2    28  29
          C3    30  31
A2   B0   C0    32  33
          C1    34  35
          C2    36  37
          C3    38  39
     B1   C0    40  41
          C1    42  43
          C2    44  45
          C3    46  47

我想在每个 lvl0 索引中获得特殊的 lvl1 组。在这种情况下,选择列 b 具有最大值的组,结果可能是这样的:

                 a   b
lvl0 lvl1 lvl2
A0   B1   C0     8   9
          C1    10  11
          C2    12  13
          C3    14  15
A1   B0   C0    16  47
          C1    18  49
          C2    20  41
          C3    22  43
A2   B1   C0    40  41
          C1    42  43
          C2    44  45
          C3    46  47

有没有像df[(('A0','B1'),('A1','B0'),('A2','B1')),:] 这样的索引方法?我已经尽力了,谢谢你的帮助。

【问题讨论】:

    标签: pandas multi-index


    【解决方案1】:

    你可以使用:

    df1 = df.reset_index(level=2, drop=True)
    mask = df1.index.isin(df1.groupby(level=[0])['b'].idxmax())
    df = df[mask]
    
    print (df)
                     a   b
    lvl0 lvl1 lvl2        
    A0   B1   C0     8   9
              C1    10  11
              C2    12  13
              C3    14  15
    A1   B0   C0    16  47
              C1    18  49
              C2    20  41
              C3    22  43
    A2   B1   C0    40  41
              C1    42  43
              C2    44  45
              C3    46  47
    

    解释:

    首先将reset_indexgroupbyidxmax 删除3 级MultiIndex 以获取b 列中最大值的索引:

    df1 = df.reset_index(level=2, drop=True)
    idx = df1.groupby(level=[0])['b'].idxmax()
    print (idx)
     lvl0
    A0    (A0, B1)
    A1    (A1, B0)
    A2    (A2, B1)
    Name: b, dtype: object
    

    然后通过isin比较创建布尔掩码:

    print (df1.index.isin(idx))
    [False False False False  True  True  True  True  True  True  True  True
     False False False False False False False False  True  True  True  True]
    

    最后由boolean indexing过滤:

    df = df[df1.index.isin(idx)]
    print (df)
                     a   b
    lvl0 lvl1 lvl2        
    A0   B1   C0     8   9
              C1    10  11
              C2    12  13
              C3    14  15
    A1   B0   C0    16  47
              C1    18  49
              C2    20  41
              C3    22  43
    A2   B1   C0    40  41
              C1    42  43
              C2    44  45
              C3    46  47
    

    【讨论】:

    • 是的,groupby 和布尔索引是正确的方法。
    猜你喜欢
    • 2021-10-03
    • 2019-01-26
    • 2016-10-16
    • 2019-01-19
    • 1970-01-01
    • 2015-12-24
    • 2021-11-11
    • 2023-02-10
    • 2018-08-04
    相关资源
    最近更新 更多