To get the average of each numeric column and row in Pandas DataFrame (apply only for numeric values):
Average each column:
df.mean(axis=0)
Average each row:
df.mean(axis=1)
Steps to get the Average of each Column and Row in Pandas DataFrame
Step 1: Prepare the data
For example, here is a simple dataset that contains information about the commission earned by 3 people (over the first 6 months of the year):
month | a_commission | b_commission | c_commission |
Jan | 7000 | 10000 | 3000 |
Feb | 5500 | 7500 | 6000 |
Mar | 6000 | 6500 | 4500 |
Apr | 4500 | 6000 | 4500 |
May | 8000 | 9000 | 4000 |
Jun | 6000 | 8500 | 5500 |
The goal is to get the average commission earned:
- For each person over the first 6 months (average by column)
- For each month across all people (average by row)
Step 2: Get the Average of each Column and Row in Pandas DataFrame
To get the average of each numeric column using df.mean(axis=0):
import pandas as pd data = {"month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], "a_commission": [7000, 5500, 6000, 4500, 8000, 6000], "b_commission": [10000, 7500, 6500, 6000, 9000, 8500], "c_commission": [3000, 6000, 4500, 4500, 4000, 5500] } df = pd.DataFrame(data, columns=["a_commission", "b_commission", "c_commission"]) df_avg = df.mean(axis=0) print(df_avg)
The average commission per person:
a_commission 6166.666667
b_commission 7916.666667
c_commission 4583.333333
To get the average of each numeric row using df.mean(axis=1):
import pandas as pd data = {"month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"], "a_commission": [7000, 5500, 6000, 4500, 8000, 6000], "b_commission": [10000, 7500, 6500, 6000, 9000, 8500], "c_commission": [3000, 6000, 4500, 4500, 4000, 5500] } df = pd.DataFrame(data, columns=["a_commission", "b_commission", "c_commission"]) df_avg = df.mean(axis=1) print(df_avg)
The average commission earned per month:
0 6666.666667
1 6333.333333
2 5666.666667
3 5000.000000
4 7000.000000
5 6666.666667
The following guide explains the steps to get the sum of each column and row in Pandas DataFrame.