列上的 Pandas Multiindex Groupby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40745981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas Multiindex Groupby on Columns
提问by Bobe Kryant
Is there anyway to use groupby on the columns in a Multiindex. I know you can on the rows and there is good documentationin that regard. However I cannot seem to groupby on columns. The only solution I have is transposing the dataframe.
无论如何在多索引中的列上使用 groupby 。我知道你可以在行上,并且在这方面有很好的文档。但是我似乎无法对列进行分组。我唯一的解决方案是转置数据帧。
#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?
那么有没有办法在不移调的情况下做到这一点?