在具有单级别的 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 ......
慕的地6264312
相关分类