在具有单级别的 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 efghA 1.014831 1.274621 -1.490353 -0.954438B 1.484857 -0.968642 0.700881 -3.281607C 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 efghA 6.583721 -1.554734 1.922187 1.100208B 6.138441 0.653721 -0.204472 1.890755C 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 ......
1 回答
慕的地6264312
TA贡献1817条经验 获得超6个赞
一种方法是将函数传递给groupby,然后将元组转换回 MultiIndex
out = df2.groupby(lambda x: (x[0], dict_col[x[1]]), axis=1).sum()
out.columns = pd.MultiIndex.from_tuples(out.columns)
stack另一种方法是在之后unstack将列级别展平groupby:
df2.stack(level=0).groupby(dict_col, axis=1).sum().unstack(level=-1)
添加回答
举报
0/150
提交
取消