python - 多级索引中的聚合

标签 python pandas pandas-groupby

我有一个具有两级列索引的数据框。我需要在两个键(列)上有不同的聚合函数。但是,我的代码收到错误。如何聚合多级数据框中的多个列。

dic1 = {('count', 'N.A.'): {Period('1993-01', 'M'): 0,
  Period('1993-02', 'M'): 0,
  Period('1993-03', 'M'): 0},
 ('count', 'No'): {Period('1993-01', 'M'): 1,
  Period('1993-02', 'M'): 1,
  Period('1993-03', 'M'): 1},
 ('count', 'Yes'): {Period('1993-01', 'M'): 0,
  Period('1993-02', 'M'): 0,
  Period('1993-03', 'M'): 0},
 ('sum', 'N.A.'): {Period('1993-01', 'M'): nan,
  Period('1993-02', 'M'): nan,
  Period('1993-03', 'M'): nan},
 ('sum', 'No'): {Period('1993-01', 'M'): 6.5820000000000007,
  Period('1993-02', 'M'): 131.1865,
  Period('1993-03', 'M'): 133.31049999999999},
 ('sum', 'Yes'): {Period('1993-01', 'M'): nan,
  Period('1993-02', 'M'): nan,
  Period('1993-03', 'M'): nan}}

df1 = pd.DataFrame(dic1)

df1.to_timestamp(how='end').groupby(pd.TimeGrouper('A') ).agg(
{'count':['max', 'min', 'median', 'last'] , 
 'sum':['mean', 'max' , 'last']} )

error:  KeyError: 'sum' 

enter image description here

最佳答案

一种巧妙的方法是分别提取所有计数和总和列:

In [11]: agg_dict = {col: ['mean', 'max' , 'median', 'last'] for col in df1.columns[df1.columns.get_level_values(0) == "count"]}

In [12]: agg_dict.update({col: ['mean', 'max' , 'last'] for col in df1.columns[df1.columns.get_level_values(0) == "sum"]})

In [13]: g = df1.to_timestamp(how='end').groupby(pd.TimeGrouper('A') )

In [14]: g.agg(agg_dict)
Out[14]:
            sum                                                       count
           N.A.                  No                      Yes           N.A.                   No                  Yes
           mean max last       mean       max      last mean max last  mean max median last mean max median last mean max median last
1993-12-31  NaN NaN  NaN  90.359667  133.3105  133.3105  NaN NaN  NaN     0   0      0    0    1   1      1    1    0   0      0    0

关于python - 多级索引中的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46837734/

相关文章:

Python脚本完成退出

python - Pandas:从 3 列创建时间戳:月、日、小时

python - 如何将 statsmodels 的 VAR 函数拟合的对数差分数据转换回实际值

python - 带分隔符的 Pandas groupby 连接

python - 类型错误 : list indices must be integers, 不是字符串。除非它是一个整数

python - python3.9上的pip3在 'HTMLParser'对象没有属性 'unescape'上失败

python - 尝试使用 PyOpengl 使用索引和顶点绘制简单的正方形

python - 如何按类别绘制平均值条形图

python - Pandas groupby multiindex 在第一级唯一时 : unexpected results

PYTHON - PANDAS - Groupby 更新行值