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!
CodePudding user response:
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
CodePudding user response:
Try this:
df.loc['Total'] = df.sum()