Calculate Quantiles in Python – Quartile of List & DataFrame (3 Examples)

In this Python programming tutorial you’ll learn how to get quantiles of a list or a pandas DataFrame column.

Example 1: Calculating the Quantiles 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.quantile(my_lt, np.arange(0.25, 1, 0.25)))             # Computing the quartiles of a list
# [ 3.  6. 10.]

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

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
print(my_df.quantile(np.arange(0.1, 1, 0.1)))                   # Computing the deciles of all columns
#         A    B    C
# 0.1  10.6  2.2  2.6
# 0.2  11.2  3.4  3.2
# 0.3  11.8  4.6  3.8
# 0.4  12.4  5.4  4.4
# 0.5  13.0  6.0  5.0
# 0.6  13.6  7.2  5.6
# 0.7  14.2  8.0  6.2
# 0.8  14.8  8.0  6.8
# 0.9  15.4  8.4  7.4

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

print(my_df.groupby('GRP').quantile(np.arange(0.25, 1, 0.25)))  # Computing the column quartiles by group
#               A     B     C
# GRP                        
# gr1 0.25  11.00  4.50  3.00
#     0.50  12.00  6.00  4.00
#     0.75  13.00  7.00  5.00
# gr2 0.25  12.00  2.75  4.00
#     0.50  13.00  4.50  5.00
#     0.75  14.00  6.25  6.00
# gr3 0.25  13.75  6.00  5.75
#     0.50  14.50  7.00  6.50
#     0.75  15.25  8.00  7.25

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