pandas 多索引分组依据 [英] Pandas Multiindex Groupby on Columns
本文介绍了 pandas 多索引分组依据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无论如何,在Multiindex的列上是否可以使用groupby.我知道您可以在行上找到一个很好的文档在这方面.但是我似乎无法按列分组.我唯一的解决方案是转置数据框.
Is there anyway to use groupby on the columns in a Multiindex. I know you can on the rows and there is good documentation in that regard. However I cannot seem to groupby on columns. The only solution I have is transposing the dataframe.
#generate data (copied from pandas example)
arrays=[['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
现在,我将尝试对失败的列进行分组
Now I will try to groupby columns which fails
df.groupby(level=1)
df.groupby(level='first')
但是与行进行转置是可行的
However transposing with rows works
df.T.groupby(level=1)
df.T.groupby(level='first')
那么有没有一种方法可以不进行转置?
So is there a way to do this without transposing?
推荐答案
您需要在groupby
方法中指定轴:
You need to specify the axis in the groupby
method:
df.groupby(level = 1, axis = 1).sum()
或者如果您是按0级分组的话:
Or if you mean groupby level 0:
df.groupby(level = 0, axis = 1).sum()
这篇关于 pandas 多索引分组依据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文