Skip to content Skip to sidebar Skip to footer

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]:
              company1  company2
April- 2012        112       112
April- 2013       1054      1054
April- 2014        573       573
August- 2012       431       431
August- 2013       496       496
August- 2014       724       724

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"