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
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
Asked: 2021-12-20 11:00:00 +0000
Seen: 9 times
Last updated: Oct 03 '21
How can Django Admin accommodate a variety of formats and locales for its input fields?
How can an array be passed using typo3 flexform xml and itemsProcConfig?
Is it possible to invoke an asynchronous function without using the await keyword?
How can metadata be linked to a series in Polars?
What is the process of utilizing the map function to map a pandas column using a dictionary?
How can the orientation of images be corrected during uploading using Plupload?