简体   繁体   English

计算熊猫中多索引DataFrame每列的最小值

[英]Calculate minimum value for each column of multi-indexed DataFrame in pandas

I have a multi-indexed DataFrame with the following structure: 我有一个具有以下结构的多索引DataFrame:

         metric1                 metric2            
     experiment1 experiment2 experiment1 experiment2
run1         1.2         1.5         0.2         0.9
run2         2.1         0.7         0.4         4.3

How can I calculate minimum (maximum, mean, etc.) value for each column and get DataFrame like this: 如何计算每列的最小值(最大值,平均值等),并按如下方式获取DataFrame:

         metric1                 metric2            
     experiment1 experiment2 experiment1 experiment2
run1         1.2         1.5         0.2         0.9
run2         1.6         0.9         0.3         3.1
run3         2.1         0.7         0.4         4.3
min          1.2         0.7         0.2         0.9
max          2.1         1.5         0.4         4.3

You can take the min, max, and mean then use pd.concat to stitch everything together. 您可以采用最小值,最大值和平均值,然后使用pd.concat将所有内容拼接在一起。 You'll need to transpose (T) then transpose back to get the dataframe to concat the way you want. 您需要先转置(T),然后转回,以使数据帧以所需的方式连接。

In [91]: df = pd.DataFrame(dict(exp1=[1.2,2.1],exp2=[1.5,0.7]), index=["run1", "run2"])

In [92]: df_min, df_max, df_mean = df.min(), df.max(), df.mean()

In [93]: df_min.name, df_max.name, df_mean.name = "min", "max", "mean"

In [94]: pd.concat((df.T, df_min, df_max, df_mean), axis=1).T
Out[94]:
      exp1  exp2
run1  1.20   1.5
run2  2.10   0.7
min   1.20   0.7
max   2.10   1.5
mean  1.65   1.1

Should work the same with a multi-index. 应该与多索引相同。

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

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