Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum the rows of a dataframe and create a sub row below

I am trying to take several numbers from a few different columns of a data frame and sum them and create a new row called "Total" directly below the last line. Below are some example data that I am working with.

import pandas as pd
option = pd.DataFrame(['Option1','Option2','Option3','Option4'])
Volume = pd.DataFrame([1234,23423,2331,23135])
dataframe1 = pd.concat([option, Volume],axis=1)

You will see that I am looking at a two-column dataframe with the "Options" column and then a numerical value. The end goal is to have a "Total" column at the end of the option 4 row this will need to be an aggregate of all the numbers in Options 1-4. Please let me know the best way to go about this! Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

totalcount = dataframe1.iloc[:,1].sum()
dataframe1.loc[len(dataframe1.index)] = ['Total', totalcount]  # This is for Row
dataframe1["Total"] = totalcount  # This is for Column
print(dataframe1)

Screenshot showing column output and row output (50123 for all values)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading