【问题标题】:Pandas grouping by heirarchical multiindex without losing other indicesPandas 按分层多索引分组而不丢失其他索引
【发布时间】:2017-12-12 01:31:21
【问题描述】:

我有一个带有分层多索引的 Pandas DataFrame,如下所示:

In [1]: df
S                         A         A         B         B         C
foo                       1         2         3         4         5 
bar                      10        20        30        40        50 
2016-09-25          0.09321  0.101425  0.129751  0.129751  0.098990
2016-10-06          0.09321  0.101425  0.091678  0.091678  0.030795
2016-10-18          0.09321  0.101425  0.143422  0.143422  0.045204
2016-10-25          0.09321  0.101425  0.103444  0.103444  0.045911

其中Sfoobar 是层次索引,日期是实际的DataFrame 索引。

我想按 S 进行分组,并将分层索引与数据框相同,以便 df.sumdf.groupby(level=0,axis=1).sum() 版本看起来像这样,包括 foobar 行:

S                         A         B         C
foo                       3         7         5
bar                      30        70        50
2016-09-25         0.194635  0.259502  0.098990
2016-10-06         0.194635  0.183356  0.030795
2016-10-18         0.194635  0.286844  0.045204
2016-10-25         0.194635  0.206887  0.045911

【问题讨论】:

  • 你希望 foo 和 bar 在 sum 之后如何?
  • 原始数据框上的stack(0)groupby(level=0) 是否为您提供所需的内容?
  • @Wen:按组求和S?如果将它们作为操作的 DataFrame 数据处理,然后返回到分层索引,那就没问题了。
  • @Andrew:不,它没有。如果我这样做,S 没有分组(或求和或含义)。我还有 5 列。

标签: python pandas dataframe


【解决方案1】:

让我们试试这个(注意:如果列索引的级别 1 和 2 的 dtype 已经是 int,您可能不需要 .apply(pd.to_numeric))。

dict1 = dict((i,'mean') for i in df.index)
dict1['foo'] = 'sum'
dict1['bar'] = 'sum'

df.T.reset_index().apply(pd.to_numeric)\
  .groupby('S').agg(dict1)\
  .set_index(['foo','bar'], append=True).T

输出:

S                 13        14        15
foo               49        53        28
bar              202       215       94 
2016-10-06  0.097318  0.091678  0.030795
2016-10-18  0.097318  0.143422  0.045204
2016-09-25  0.097318  0.129751  0.098990
2016-10-25  0.097318  0.103444  0.045911

有问题的新数据:

dict1 = dict((i,'mean') for i in df.index)
dict1['foo'] = 'sum'
dict1['bar'] = 'sum'

print(df.T.reset_index(level=[1,2]).apply(pd.to_numeric)
        .groupby('S').agg(dict1)
        .set_index(['foo','bar'], append=True).T)

输出:

S                  A         B         C
foo                3         7         5
bar               30        70        50
2016-10-06  0.097318  0.091678  0.030795
2016-10-18  0.097318  0.143422  0.045204
2016-09-25  0.097318  0.129751  0.098990
2016-10-25  0.097318  0.103444  0.045911

【讨论】:

  • 不完全... S 未分组。 foobar 也可以平均吗?
  • @mankoff 你能简单地展示你的数据并准确地展示你的期望吗?组成一些简单的数字和结构。很不清楚你在问什么。
  • 我已经编辑了这个问题。抱歉,不清楚。我已经准确地放置了我想要实现的数据框。
  • @mankoff 'foo' 和 'bar' 字符串或整数的数据类型是什么?
  • 哇。有用。我需要一段时间才能理解——这似乎并不简单,因为我认为这是一个相当简单的操作。谢谢!
猜你喜欢
  • 2021-02-03
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 2019-01-12
  • 2021-02-02
相关资源
最近更新 更多