如何为多索引DataFrame的每个级别查找最大绝对值

时间:2019-08-23 16:11:11

标签: python pandas dataframe

如何找到多索引数据帧每个级别的最大绝对值?

数据如下:

                        data
            a   b   c   
            1   X   1   -2
                X   2   +2
            2   X   1   -1
                X   2   +2
                Y   1   +6
            3   X   1   -5
                Y   1   -3
                Y   2   +5

这是我希望在保持多重索引的第1级和第2级的同时收到的信息:

                        data
                a   b   
                1   X   2
                2   X   2
                    Y   6   
                3   X   -5
                    Y   +5

1 个答案:

答案 0 :(得分:1)

使用idxmax

idx = df['data'].abs().groupby(level=[0,1]).idxmax()
df.loc[idx]

结果:

       data
a b c      
1 X 1    -2
2 X 2     2
  Y 1     6
3 X 1    -5
  Y 2     5

外植:

idx = df['data'].abs()          # convert the `data` column to its absolute value
        .groupby(level=[0,1])   # group by the first two levels (`a` and `b`)
        .idxmax()               # find the index of the row with max value in each group
df.loc[idx]                     # get the rows at indexes `idx`