如何为多索引数据帧的每个级别找到最大绝对值?
数据如下所示:
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
最佳答案
使用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`
关于python - 如何为多索引DataFrame的每个级别查找最大绝对值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57629793/