【问题标题】:Groupby multiindex columns using dictionaryGroupby 使用字典的多索引列
【发布时间】:2021-02-11 12:39:08
【问题描述】:

在具有单个级别的 DataFrame 上,使用字典对列上的数据进行分组:

df1 = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=['a','b','c','d','e','f','g','h'])
dict_col= {'a':'ab','b':'ab','c':'c','d':'d','e':'efgh','f':'efgh','g':'efgh','h':'efgh'}
df1.groupby(dict_col, axis=1).sum()
    ab          c           d           efgh
A   1.014831    1.274621    -1.490353   -0.954438
B   1.484857    -0.968642   0.700881    -3.281607
C   0.898556    1.444362    0.680974    -2.985182

在多索引数据帧上:

MultiIndex = pd.MultiIndex.from_product([['bar', 'baz', 'foo', 'qux'], ['a','b','c','d','e','f','g','h']])
df2 = pd.DataFrame(np.random.randn(3, 32), index=['A', 'B', 'C'], columns=MultiIndex)
df2.groupby(dict_col, axis=1, level=1).sum()
    ab          c           d           efgh
A   6.583721    -1.554734   1.922187    1.100208
B   6.138441    0.653721    -0.204472   1.890755
C   0.951489    2.695940    -1.494028   0.907464

如何得到这样的东西(0级的所有元素)?

    bar                                            baz                                              foo
    ab          c           d           efgh       ab           c           d           efgh        ......    
A   6.583721    -1.554734   1.922187    1.100208   4.944954     -1.343831   0.939265    -3.614612   ......
B   6.138441    0.653721    -0.204472   1.890755   -0.347505    1.633708    0.392096    0.414880    ......
C   0.951489    2.695940    -1.494028   0.907464   1.905409     -1.021097   -2.399670   0.799798    ......

【问题讨论】:

    标签: python pandas dictionary pandas-groupby multi-index


    【解决方案1】:

    一种方法是将函数传递给groupby,然后将元组转换回MultiIndex

    out = df2.groupby(lambda x: (x[0], dict_col[x[1]]), axis=1).sum()
    out.columns = pd.MultiIndex.from_tuples(out.columns)
    

    另一种方法是在groupby 之后将列级别展平stack 然后unstack 回到groupby

    df2.stack(level=0).groupby(dict_col, axis=1).sum().unstack(level=-1)
    

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 1970-01-01
      • 2018-12-01
      • 2022-10-26
      • 2019-01-26
      • 2017-03-08
      • 2021-07-13
      • 2020-09-09
      • 1970-01-01
      相关资源
      最近更新 更多