【问题标题】:How to access multiindex levels in pandas?如何访问熊猫中的多索引级别?
【发布时间】:2016-04-25 07:03:36
【问题描述】:

我想计算出每一列“一”和“二”的平均值。

这是我的数据框上的 df.columns 语句的结果:

MultiIndex(levels=[['Growth %'], ['One', 'Two']],
       labels=[[0, 0], [0, 1]],
       names=[None, 'Years'])

我基本上想计算出“一”和“二”列中所有数值的平均值。

如果我这样做:

df.mean(axis=0)

我明白了:

Years
Growth %   One 17.215293

           Two 45.213257

dtype: float64

但我只想要这些列的单个值,以便将它们添加到数据框中。

我已经尝试过:

df.mean(levels=[['Growth %'], ['One']])

还有类似的变化,但我无法显示这些单独列的平均值。

任何帮助都非常感谢。

【问题讨论】:

  • 你能分享一个你正在使用的 df 样本吗?这会很有帮助。

标签: python pandas dataframe


【解决方案1】:

所以,这就是我以前重新构建的:

In [17]: index = pd.MultiIndex(levels=[['Growth %'], ['One', 'Two']], labels=[[0, 0], [0, 1]], names=[None, 'Years'])

In [18]: df = pd.DataFrame(np.random.randn(2,6), index=index)

In [19]: df
Out[19]: 
                       0         1         2         3         4         5
         Years                                                            
Growth % One    0.449989  0.008239 -0.212202 -1.829215  0.609796  0.922987
         Two   -0.819815  0.726769  0.150591  1.851841 -0.639491 -0.637081

In [26]: df.mean(axis=1)
Out[26]: 
          Years
Growth %  One     -0.008401
          Two      0.105469
dtype: float64

也就是说,刚刚返回的是一个pd.Series,你可以使用正确的索引来获取正确的数据。

试试这个:

df.mean(axis=1)['Growth %']['One']
df.mean(axis=1)['Growth %']['Two']

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 2019-05-03
    • 2023-04-02
    • 1970-01-01
    • 2013-12-04
    • 2020-12-05
    • 2022-01-13
    相关资源
    最近更新 更多