2016-11-22 103 views
1

無論如何都要在Multiindex的列上使用groupby。我知道你可以在行上,在這方面有很好的documentation。不過,我似乎無法在專欄上分組。我唯一的解決方案是轉置數據幀。Pandas Multiindex Groupby on專欄

#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) 

現在,我會盡量GROUPBY列從而未能

df.groupby(level=1) 
df.groupby(level='first') 

然而,隨着行調換工作

df.T.groupby(level=1) 
df.T.groupby(level='first') 

那麼,有沒有辦法做到這一點而不調換?

回答

4

您需要在groupby方法指定軸:

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

enter image description here

或者,如果你的意思是GROUPBY級別0:

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

enter image description here