Get Column & Row Means of pandas DataFrame in Python (2 Examples)

In this tutorial you’ll learn how to compute the column and row means of a pandas DataFrame in the Python programming language.

Setting up the Examples

import pandas as pd                               # Import pandas library to Python
my_df = pd.DataFrame({'A':[1, 2, 4, 5, 2, 7],    # Construct example DataFrame
                      'B':[5, 1, 8, 1, 9, 2],
                      'C':[1, 2, 1, 2, 1, 2]})
print(my_df)                                     # Display example DataFrame in console
#    A  B  C
# 0  1  5  1
# 1  2  1  2
# 2  4  8  1
# 3  5  1  2
# 4  2  9  1
# 5  7  2  2

Example 1: Computing Column Means for pandas DataFrame

print(my_df.mean())                              # Column means
# A    3.500000
# B    4.333333
# C    1.500000
# dtype: float64

Example 2: Computing Row Means for pandas DataFrame

print(my_df.mean(axis = 1))                      # Row means
# 0    2.333333
# 1    1.666667
# 2    4.333333
# 3    2.666667
# 4    4.000000
# 5    3.666667
# dtype: float64

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top