0

I am currently trying to add totals to the bottom of my columns in preparation for my dataframes to be exported to excel/CSV files. I wanted to know what the best way to do this is.

I had been using Wilhelm['Amount'].sum(), but this is not very efficient as I have to re-add them after I export every time.

Thank you!

Rodalm
  • 5,169
  • 5
  • 21
max2lax
  • 5
  • 2
  • Please share snippet it will be helpful. How many columns are there in DataFrame? Do you want sum of all columns? or you only want to add sum of `Wilhelm['Amount'].sum()`? It's ambiguous question. – GodWin1100 Jun 28 '22 at 23:06
  • Always provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) when asking for help, so people can understand clearly what you want and reproduce the problem. Please take the time to read [how to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask), and revise your question accordingly. – Rodalm Jun 28 '22 at 23:09

2 Answers2

0

Let's say you have a dataframe of the form:

    Jan Feb Mar Apr May Jun
Budget                      
Milk    10  20  31  52  7   11
Eggs    1   5   1   16  4   58
Bread   22  36  17  8   21  16
Butter  4   5   8   11  36  2 

And you would like to add a Total row at the bottom which contains the sum of the columns. This is how I would do this task.

# Append a new row containing sum of each column
df.append(pd.Series(df.sum(numeric_only= True),name='Total'))

This will produce the dataframe of the following format.

    Jan Feb Mar Apr May Jun
Budget                          
Milk    10  20  31  52  7   11
Eggs    1   5   1   16  4   58
Bread   22  36  17  8   21  16
Butter  4   5   8   11  36  2
Total   37  66  57  87  68  87

As was pointed out by @kevin-choon-liang-yew, append is scheduled for depreciation, in which case you would need to use the concat function to append a new row as shown below:

 pd.concat([df, pd.DataFrame(pd.Series(df.sum(numeric_only= True)).to_dict(),index=['Total'])]) 

returning the final dataframe.

itprorh66
  • 3,110
  • 4
  • 9
  • 21
0

Try this:

df.loc['Total'] = df.sum()
rhug123
  • 7,893
  • 1
  • 9
  • 24