简体   繁体   English

列上的Pandas Multiindex Groupby

[英]Pandas Multiindex Groupby on Columns

Is there anyway to use groupby on the columns in a Multiindex. 无论如何在Multiindex的列上使用groupby。 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? 那么有没有办法在没有移调的情况下做到这一点?

You need to specify the axis in the groupby method: 您需要在groupby方法中指定轴:

df.groupby(level = 1, axis = 1).sum()

在此输入图像描述

Or if you mean groupby level 0: 或者,如果你的意思是groupby 0级:

df.groupby(level = 0, axis = 1).sum()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM