How to Calculate the Mean in Python – Average of List & Data (4 Examples)
In this article, I’ll illustrate how to compute the mean of a list and the columns of a pandas DataFrame in the Python programming language.
Example 1: Calculating the Mean of a List Object
my_lt = [10, 15, 20, 3, 7, 4] # Constructing a list in Python print(my_lt) # [10, 15, 20, 3, 7, 4] |
my_lt = [10, 15, 20, 3, 7, 4] # Constructing a list in Python print(my_lt) # [10, 15, 20, 3, 7, 4]
import numpy as np # Import NumPy library in Python |
import numpy as np # Import NumPy library in Python
print(np.mean(my_lt)) # Computing the mean of a list # 9.833333333333334 |
print(np.mean(my_lt)) # Computing the mean of a list # 9.833333333333334
Example 2: Calculating the Mean of the Columns in a pandas DataFrame
import pandas as pd # Load pandas |
import pandas as pd # Load pandas
my_df = pd.DataFrame({'A':range(10, 17), # Constructing a pandas DataFrame 'B':[6, 1, 8, 5, 3, 8, 9], 'C':range(2, 9), 'GRP':['gr1', 'gr2', 'gr1', 'gr3', 'gr1', 'gr2', 'gr3']}) print(my_df) # A B C GRP # 0 10 6 2 gr1 # 1 11 1 3 gr2 # 2 12 8 4 gr1 # 3 13 5 5 gr3 # 4 14 3 6 gr1 # 5 15 8 7 gr2 # 6 16 9 8 gr3 |
my_df = pd.DataFrame({'A':range(10, 17), # Constructing a pandas DataFrame 'B':[6, 1, 8, 5, 3, 8, 9], 'C':range(2, 9), 'GRP':['gr1', 'gr2', 'gr1', 'gr3', 'gr1', 'gr2', 'gr3']}) print(my_df) # A B C GRP # 0 10 6 2 gr1 # 1 11 1 3 gr2 # 2 12 8 4 gr1 # 3 13 5 5 gr3 # 4 14 3 6 gr1 # 5 15 8 7 gr2 # 6 16 9 8 gr3
print(my_df.mean()) # Computing the mean of all columns # x1 5.333333 # x2 4.000000 # dtype: float64 |
print(my_df.mean()) # Computing the mean of all columns # x1 5.333333 # x2 4.000000 # dtype: float64
Example 3: Calculating the Mean of the Columns in a pandas DataFrame by Group
print(my_df.groupby('GRP').mean()) # Computing the column means by group # A B C # GRP # gr1 12.0 5.666667 4.0 # gr2 13.0 4.500000 5.0 # gr3 14.5 7.000000 6.5 |
print(my_df.groupby('GRP').mean()) # Computing the column means by group # A B C # GRP # gr1 12.0 5.666667 4.0 # gr2 13.0 4.500000 5.0 # gr3 14.5 7.000000 6.5
Example 4: Calculating the Mean of the Rows in a pandas DataFrame
print(my_df.mean(axis = 1)) # Computing the mean of all rows # 0 6.000000 # 1 5.000000 # 2 8.000000 # 3 7.666667 # 4 7.666667 # 5 10.000000 # 6 11.000000 # dtype: float64 |
print(my_df.mean(axis = 1)) # Computing the mean of all rows # 0 6.000000 # 1 5.000000 # 2 8.000000 # 3 7.666667 # 4 7.666667 # 5 10.000000 # 6 11.000000 # dtype: float64