Reputation: 91
I have a multi indexed pandas dataframe like -
a b c
c1 c2 c1 c2 c1 c2
9 10.0 162 165 16 15.0
I want to create another column which would contain sum of c1 columns and c2 columns for that row like -
a b c total
c1 c2 c1 c2 c1 c2 c1 c2
9 10.0 162 165 16 15.0 187 190
How to I achieve the same considering there can be n number of level 1 columns (a,b,c,d...) and n number of level 2 columns (c1,c2,c3,c4...)
Thanks!
Upvotes: 0
Views: 61
Reputation: 71689
Let us try stack
to reshape then assign
the total
column by summing along the columns axis, then unstack
to reshape back
s = df.stack()
s.assign(total=s.sum(1)).unstack()
a b c total
c1 c2 c1 c2 c1 c2 c1 c2
0 9.0 10.0 162 165 16.0 15.0 187.0 190.0
Upvotes: 2
Reputation: 14949
Here's one way:
level=1
and axis=1
pd.concat
to join the result with your original df.df1 = df.sum(level=1, axis=1)
df1.columns = pd.MultiIndex.from_product([['total'], df1.columns])
df = pd.concat([df, df1], 1)
a b c total
c1 c2 c1 c2 c1 c2 c1 c2
0 9 10.0 162 165 16 15.0 187.0 190.0
Upvotes: 3