How to Add a Total Row to Pandas DataFrame

To add a total row to a Pandas DataFrame, you first need to use the pandas.DataFrame.sum() method to generate the total for each column, and then use the pandas.DataFrame.append() method to add the totals to the bottom of the DataFrame. The result is a DataFrame with a new row containing the column totals. To make the total row more visible, you can use the pandas.DataFrame.style.set_properties() method to highlight the total row.


You can use the following basic syntax to add a ‘total’ row to the bottom of a pandas DataFrame:

df.loc['total']= df.sum()

The following example shows how to use this syntax in practice.

Example: Add a Total Row to Pandas DataFrame

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F'],
                   'assists': [5, 7, 7, 9, 12, 9],
                   'rebounds': [11, 8, 10, 6, 6, 5],
                   'blocks': [6, 6, 3, 2, 7, 9]})

#view DataFrame
print(df)

  team  assists  rebounds  blocks
0    A        5        11       6
1    B        7         8       6
2    C        7        10       3
3    D        9         6       2
4    E       12         6       7
5    F        9         5       9

We can use the following syntax to add a ‘total’ row at the bottom of the DataFrame that shows the sum of values in each column:

#add total row
df.loc['total']= df.sum()

#view updated DataFrame
print(df)

         team  assists  rebounds  blocks
0           A        5        11       6
1           B        7         8       6
2           C        7        10       3
3           D        9         6       2
4           E       12         6       7
5           F        9         5       9
total  ABCDEF       49        46      33

A new row has been added to the bottom of the DataFrame that shows the sum of values in each column.

Note that for character columns, the ‘total’ is simply the concatenation of every character in the column.

If you’d like, you can set the ‘total’ value in the team column to simply be blank:

#set last value in team column to be blank
df.loc[df.index[-1], 'team'] = ''

#view updated DataFrame
print(df)

      team  assists  rebounds  blocks
0        A        5        11       6
1        B        7         8       6
2        C        7        10       3
3        D        9         6       2
4        E       12         6       7
5        F        9         5       9
total            49        46      33

The last value in the team column is now blank, as opposed to being a concatenation of every character in the column.

x