[英]Get values of columns and groups of a pandas grouped DataFrame
I have a grouped pandas DataFrame as follows: 我有一个分组的熊猫DataFrame,如下所示:
Fx Fy Fz Mx My Mz
Model Group Support Node
Reactions 00 G P1 1 -3.0 3.0 170.0 0.0 -23.0 -1.0
P2 3 6.0 11.0 180.0 0.0 -15.0 -1.0
4 -1.0 19.0 115.0 0.0 -7.0 -1.0
Q P1 1 -1.0 7.0 550.0 0.0 -19.0 -1.0
P2 3 2404.0 15.0 2005.0 0.0 -11.0 -1.0
4 2736.0 23.0 -2995.0 0.0 -3.0 -1.0
Reactions 01 D P1 1 -1.0 -9.0 -1.0 0.0 23.0 -1.0
P2 3 -7.0 -19.0 140.0 0.0 13.0 1.0
4 -5.0 -29.0 -3950.0 0.0 3.0 1.0
G P1 1 -1.0 -1.0 10.0 0.0 15.0 -1.0
P2 3 -6.0 -6.0 10.0 0.0 10.0 6.0
4 4.0 -11.0 100.0 0.0 5.0 -11.0
Q P1 1 0.0 -5.0 400.0 0.0 27.0 -1.0
P2 3 -86.0 -15.0 -95.0 0.0 17.0 1.0
4 -110.0 -25.0 135.0 0.0 7.0 -1.0
I'd like to get for each Group and Support the máximum value of each column, but also the related Model and Node. 我想为每个组获取并支持每列的最大价值,以及相关的模型和节点。 That is:
那是:
Group Support -> Fx,max -> Model Node
G P1 -> -1.0 -> Reactions 01 1
G P2 -> 6.0 -> Reactions 00 3
Q P1 -> 0.0 -> Reactions 01 1
Q P2 -> 2736.0 -> Reactions 00 4
And so on for each column Fx to Mz. 以此类推,从Fx到Mz的每一列。
You can groupby index level, and call custom lambda
functions. 您可以对索引级别进行分组,并调用自定义
lambda
函数。 Pass these lambda
's as a tuple to control column heading and use the idxmax
aggregation function: 将这些
lambda
作为元组传递来控制列标题,并使用idxmax
聚合函数:
df.groupby(level=[1, 2]).agg(['max',
('model', lambda x: x.idxmax()[0]),
('node', lambda x: x.idxmax()[3])])
[out] [出]
Fx Fy Fz \
max model node max model node max
Group Support
D P1 -1.0 Reactions 01 1.0 -9.0 Reactions 01 1.0 -1.0
P2 -5.0 Reactions 01 4.0 -19.0 Reactions 01 3.0 140.0
G P1 -1.0 Reactions 01 1.0 3.0 Reactions 00 1.0 170.0
P2 6.0 Reactions 00 3.0 19.0 Reactions 00 4.0 180.0
Q P1 0.0 Reactions 01 1.0 7.0 Reactions 00 1.0 550.0
P2 2736.0 Reactions 00 4.0 23.0 Reactions 00 4.0 2005.0
Mx My \
model node max model node max model
Group Support
D P1 Reactions 01 1.0 0.0 Reactions 01 1.0 23.0 Reactions 01
P2 Reactions 01 3.0 0.0 Reactions 01 3.0 13.0 Reactions 01
G P1 Reactions 00 1.0 0.0 Reactions 00 1.0 15.0 Reactions 01
P2 Reactions 00 3.0 0.0 Reactions 00 3.0 10.0 Reactions 01
Q P1 Reactions 00 1.0 0.0 Reactions 00 1.0 27.0 Reactions 01
P2 Reactions 00 3.0 0.0 Reactions 00 3.0 17.0 Reactions 01
Mz
node max model node
Group Support
D P1 1.0 -1.0 Reactions 01 1.0
P2 3.0 1.0 Reactions 01 3.0
G P1 1.0 -1.0 Reactions 00 1.0
P2 3.0 6.0 Reactions 01 3.0
Q P1 1.0 -1.0 Reactions 00 1.0
P2 3.0 1.0 Reactions 01 3.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.