Summing Multiple Columns With Multiindex Columns
I have a dataframe that is created from a pivot table, and looks similar to this: import pandas as pd d = {('company1', 'False Negative'): {'April- 2012': 112.0, 'April- 2013': 370
Solution 1:
You can calculate this sum by specifying the level
(you want to sum along the first level (level 0), so collapsing the second level):
In [29]:df.sum(axis=1,level=0)Out[29]:company1company2April-2012 112112April-2013 1054 1054April-2014 573573August-2012 431431August-2013 496496August-2014 724724
If you want them to add to the original dataframe, as in your example above, you can add a level in the columns and concat:
sums = df.sum(level=0, axis=1)
sums.columns = pd.MultiIndex.from_product([sums.columns, ['SUM']])
df = pd.concat([df, sums], axis=1)
Post a Comment for "Summing Multiple Columns With Multiindex Columns"