Calculate Column & Row Sums of pandas DataFrame in Python (2 Examples)
In this tutorial, I’ll explain how to calculate the sums of all variables and rows of a pandas DataFrame in Python programming.
Setting up the Examples
import pandas as pd # Import pandas library in Python |
import pandas as pd # Import pandas library in Python
my_df = pd.DataFrame({'A':[5, 9, 1, 5, 2, 7], # Construct example DataFrame 'B':[1, 1, 1, 1, 1, 1], 'C':[1, 2, 1, 2, 1, 2]}) print(my_df) # Display example DataFrame in console # A B C # 0 5 1 1 # 1 9 1 2 # 2 1 1 1 # 3 5 1 2 # 4 2 1 1 # 5 7 1 2 |
my_df = pd.DataFrame({'A':[5, 9, 1, 5, 2, 7], # Construct example DataFrame 'B':[1, 1, 1, 1, 1, 1], 'C':[1, 2, 1, 2, 1, 2]}) print(my_df) # Display example DataFrame in console # A B C # 0 5 1 1 # 1 9 1 2 # 2 1 1 1 # 3 5 1 2 # 4 2 1 1 # 5 7 1 2
Example 1: Computing Column Sums for pandas DataFrame
print(my_df.sum()) # Column sums # A 29 # B 6 # C 9 # dtype: int64 |
print(my_df.sum()) # Column sums # A 29 # B 6 # C 9 # dtype: int64
Example 2: Computing Row Sums for pandas DataFrame
print(my_df.sum(axis = 1)) # Row sums # 0 7 # 1 12 # 2 3 # 3 8 # 4 4 # 5 10 # dtype: int64 |
print(my_df.sum(axis = 1)) # Row sums # 0 7 # 1 12 # 2 3 # 3 8 # 4 4 # 5 10 # dtype: int64