How to Add Row of Sum Of All Columns of Dataframe in Python
To add a row of the sum of all columns of a dataframe in Python, you can use the sum() function.
The following example shows how to add a row of the sum of all columns of a dataframe in Python.
Using sum() Function
We can use the sum() function to add a row of the sum of all columns of a dataframe.
Suppose we have the following dataframe:
# Import pandas library
import pandas as pd
# Create dataframe
df = pd.DataFrame({"a": [78, 85, 96, 74, 59, 69], "b": [10, 20, 30, 40, 50, 60], "c": [45, 56, 55, 65, 48, 52]})
# Add row of sum of all column data
df.loc['Total'] = df.sum()
# Show updated dataframe
print(df)
Output: 👇️
a b c
0 78 10 45
1 85 20 56
2 96 30 55
3 74 40 65
4 59 50 48
5 69 60 52
Total 461 210 321
In this example, we use the sum() function to calculate the sum of all columns and add it as a new row labeled ‘Total’.