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

Create new row index and calculate sum for each column

I have a dataframe that is shaped like this:

        com1     com2     com3
party1   10      0         0
party2   0       20       10 
party3   0       0        25

I want to create a new row index called total, and then take the sum of each column and display it like this

          com1     com2     com3
  party1   10      0         0
  party2   0       20       10 
  party3   0       0        25
Total     10       20       35

I am trying to use an apply function, but I am getting an error becuase ‘Total’ does not exist

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

df_pivot = df_pivot.apply(lambda col: df_pivot.loc['Total', col].sum())

>Solution :

Try:

df.loc["Total"] = df.sum()
print(df)

Prints:

        com1  com2  com3
party1    10     0     0
party2     0    20    10
party3     0     0    25
Total     10    20    35
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