Get Median in Python – List & pandas DataFrame Column (4 Examples)

In this tutorial you’ll learn how to compute the median for a list and the columns of a pandas DataFrame in the Python programming language.

Example 1: Calculating the Median of a List Object

my_lt = [10, 6, 2, 2, 15, 20, 3, 7, 4]      # Constructing a list in Python
print(my_lt)
# [10, 6, 2, 2, 15, 20, 3, 7, 4]
import numpy as np                          # Import NumPy
print(np.median(my_lt))                     # Computing the Median of a list
# 6.0

Example 2: Calculating the Median of the Columns in a pandas DataFrame

import pandas as pd                         # Import pandas library in Python
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.median())                       # Computing the median of all columns
# A    13.0
# B     6.0
# C     5.0
# dtype: float64

Example 3: Calculating the Median of the Columns in a pandas DataFrame by Group

print(my_df.groupby('GRP').median())        # Computing the column medians by group
#         A    B    C
# GRP                
# gr1  12.0  6.0  4.0
# gr2  13.0  4.5  5.0
# gr3  14.5  7.0  6.5

Example 4: Calculating the Median of the Rows in a pandas DataFrame

print(my_df.median(axis = 1))               # Computing the median of all rows
# 0    6.0
# 1    3.0
# 2    8.0
# 3    5.0
# 4    6.0
# 5    8.0
# 6    9.0
# dtype: float64

Leave a Reply

Your email address will not be published. Required fields are marked *

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