简体   繁体   English

熊猫:每组的最大值索引

[英]Pandas: index of max value for each group

My Pandas DataFrame, df , looks like this: 我的Pandas DataFrame, df ,看起来像这样:

parameter1   parameter2   value

1            1            0.1
             2            0.2

2            1            0.6
             2            0.3

value is the result of a groupby(['parameter1','parameter2']).mean() on another DataFrame . value是另一个DataFrame上的groupby(['parameter1','parameter2']).mean() DataFrame Now, I can find the maximum value of value for each value of parameter1 using 现在,我能找到的最大值value为每个值parameter1使用

df.max(level='parameter1')

However, I need to find the corresponding value of parameter2 for this maximum value. 但是,我需要为此最大值找到parameter2的相应值。 It seems df.idxmax() does not support level= , so how can I do this instead? 似乎df.idxmax()不支持level= ,那么我怎么能这样做呢?

A nice way would be 一个很好的方式

df.unstack().idxmax(axis=1)

Unstacking the dataframe gives a dataframe with parameter_1 as the column index. 对数据帧进行取消堆叠会给出一个带有parameter_1作为列索引的数据帧。

I eventually found a trick: 我终于找到了一个技巧:

Groupby on level 0 (parameter1) and apply idxmax() and get the values: Groupby在0级(参数1)并应用idxmax()并获取值:

v = df.groupby(level=0).idxmax().values
v
array([[(1, 2)],
       [(2, 1)]], dtype=object)

This is what df.idxmax(level=0) would give if implemented. 这就是df.idxmax(level=0)如果实现的话。

So v contains the index giving the max value for that level. 所以v包含给出该级别的最大值的索引。 So you can get the real values with: 所以你可以用以下方法获得真正的价值:

df.loc[v.ravel()]

                       value
parameter1 parameter2       
1          2             0.2
2          1             0.6

and finally get the value of parameter2 corresponding to max values: 最后得到与最大值对应的parameter2的值:

df.loc[v.ravel()].index.values[1]
(2, 1)

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM