Sum columns by level in a pandas MultiIndex DataFrame

I believe you’re looking for a groupby along the first axis.

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

On older versions of pandas, this method also works:

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

The level argument to sum implies grouping.


df

first  bar     baz     foo    
second one two one two one two
A        2   3   3   4  10   8
B       22  16   7   3   2  26
C        4   5   1   9   6   5

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

first  bar  baz  foo
A        5    7   18
B       38   10   28
C        9   10   11

Performance wise, there’s hardly any difference between the two methods outlined above (the latter is a few ticks faster).

Leave a Comment