pandas 多索引数据框-从多索引中的一个索引中选择最大值 [英] Pandas multiindex dataframe - Selecting max from one index within multiindex

查看:57
本文介绍了 pandas 多索引数据框-从多索引中的一个索引中选择最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含Year和Month的多个索引的数据框,如下所示:

I've got a dataframe with a multi index of Year and Month like the following

     |     |Value
Year |Month|  
     |  1  |  3
1992 |  2  |  5
     |  3  |  8
     | ... | ...
1993 |  1  |  2
     | ... | ...

我试图选择每年的最大值并将其放入DF这样的DF中:

I'm trying to select the maximum Value for each year and put that in a DF like this:

     | Max
Year |  
1992 |  5
1993 |  2
     | ... 

关于多索引的信息并不多,我应该简单地进行分组并应用还是要使其更简单?

There's not much info on multi-indexes, should I simply do a group by and apply or something similar to make it more simple?

推荐答案

完全正确:

df.groupby(level=0).apply(max)

在我的示例DataFrame中:


                     0
Caps Lower            
A    a     0  0.246490
           1 -1.265711
           2 -0.477415
           3 -0.355812
           4 -0.724521
     b     0 -0.409198
           1 -0.062552
           2 -0.731789
           3  1.131616
           4  0.085248
B    a     0  0.193948
           1  2.010710
           2  0.289300
           3  0.305373
           4  1.376965
     b     0  0.210522
           1  1.431279
           2 -0.247171
           3  0.899074
           4  0.639926

结果:


             0
Caps          
A     1.131616
B     2.010710

这就是我创建DataFrame的方式:

df = pd.DataFrame(np.random.randn(5,4), columns = l)
df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Caps','Lower'])
df = pd.DataFrame(df.unstack())

这篇关于 pandas 多索引数据框-从多索引中的一个索引中选择最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆