How to Add a Total Row to Pandas DataFrame


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.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

How to Select Rows without NaN Values in Pandas
How to Drop All Rows Except Specific Ones in Pandas
How to Sum Specific Columns in Pandas

Leave a Reply

Your email address will not be published.