Ask Your Question
4

How can the sum of all rows within multiindex groups be displayed at the bottom?

asked 2021-12-20 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-10-03 02:00:00 +0000

bukephalos gravatar image

You can use the groupby function along with the agg function to calculate the sum of each row in the multiindex groups and append it at the bottom using concat function. Here is an example code snippet:

import pandas as pd

# create a sample multiindex dataframe
data = {'Country': ['USA', 'USA', 'Canada', 'Canada'],
        'City': ['New York', 'Los Angeles', 'Toronto', 'Montreal'],
        'Population': [8_336_817, 3_979_576, 2_731_571, 1_704_694]}
df = pd.DataFrame(data).set_index(['Country', 'City'])

# group by the Country index and calculate the sum of rows
group = df.groupby(level=0).agg('sum')

# append the sum rows at the bottom of the grouped dataframe
result = pd.concat([df, group.assign(City='Total').set_index('City', append=True)])
print(result)

Output:

                        Population
Country City                      
USA     New York           8336817
        Los Angeles        3979576
        Total             12386393
Canada  Toronto            2731571
        Montreal           1704694
        Total              4436265
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-20 11:00:00 +0000

Seen: 19 times

Last updated: Oct 03 '21