Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending column totals to a Pandas DataFrame

Tags:

python

pandas

I have a DataFrame with numerical values. What is the simplest way of appending a row (with a given index value) that represents the sum of each column?

like image 870
user3132783 Avatar asked Dec 27 '13 17:12

user3132783


People also ask

How do you add a total to a data frame?

To get the total or sum of a column use sum() method, and to add the result of the sum as a row to the DataFrame use loc[] , at[] , append() and pandas. Series() methods.

How do I sum all the values in a column in pandas?

sum() function is used to return the sum of the values for the requested axis by the user. If the input value is an index axis, then it will add all the values in a column and works same for all the columns. It returns a series that contains the sum of all the values in each column.


2 Answers

To add a Total column which is the sum across the row:

df['Total'] = df.sum(axis=1) 
like image 157
ideate Avatar answered Sep 28 '22 08:09

ideate


To add a row with column-totals:

df.loc['Total']= df.sum() 
like image 22
BjoernL. Avatar answered Sep 28 '22 09:09

BjoernL.