Bobe Kryant Bobe Kryant - 8 months ago 95
Python Question

Pandas Multiindex Groupby on Columns

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


However transposing with rows works


So is there a way to do this without transposing?

Answer Source

You need to specify the axis in the groupby method:

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

enter image description here

Or if you mean groupby level 0:

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

enter image description here