Calculate Percentile & Decile in Python – List & DataFrame Column (4 Examples)

In this tutorial, I’ll illustrate how to get the percentiles and deciles in the Python programming language.

Example 1: Calculating the Deciles 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 library
print(np.quantile(my_lt, np.arange(0.1, 1, 0.1)))    # Computing the deciles of a list
# [ 2.   2.6  3.4  4.4  6.   6.8  8.8 12.  16. ]

Example 2: Calculating the Percentiles of a List Object

print(np.quantile(my_lt, np.arange(0.01, 1, 0.01)))  # Computing the percentiles of a list
# [ 2.    2.    2.    2.    2.    2.    2.    2.    2.    2.    2.    2.
#   2.04  2.12  2.2   2.28  2.36  2.44  2.52  2.6   2.68  2.76  2.84  2.92
#   3.    3.08  3.16  3.24  3.32  3.4   3.48  3.56  3.64  3.72  3.8   3.88
#   3.96  4.08  4.24  4.4   4.56  4.72  4.88  5.04  5.2   5.36  5.52  5.68
#   5.84  6.    6.08  6.16  6.24  6.32  6.4   6.48  6.56  6.64  6.72  6.8
#   6.88  6.96  7.12  7.36  7.6   7.84  8.08  8.32  8.56  8.8   9.04  9.28
#   9.52  9.76 10.   10.4  10.8  11.2  11.6  12.   12.4  12.8  13.2  13.6
#  14.   14.4  14.8  15.2  15.6  16.   16.4  16.8  17.2  17.6  18.   18.4
#  18.8  19.2  19.6 ]

Example 3: Calculating the Deciles of the Columns in a pandas DataFrame

import pandas as pd                                  # Import pandas library
my_df = pd.DataFrame({'A':range(100, 108),           # Constructing a pandas DataFrame
                      'B':[6, 1, 8, 7, 3, 5, 5, 9],
                      'C':range(1, 9)})
print(my_df)
#      A  B  C
# 0  100  6  1
# 1  101  1  2
# 2  102  8  3
# 3  103  7  4
# 4  104  3  5
# 5  105  5  6
# 6  106  5  7
# 7  107  9  8
print(my_df.quantile(np.arange(0.1, 1, 0.1)))        # Computing the deciles of all columns
#          A    B    C
# 0.1  100.7  2.4  1.7
# 0.2  101.4  3.8  2.4
# 0.3  102.1  5.0  3.1
# 0.4  102.8  5.0  3.8
# 0.5  103.5  5.5  4.5
# 0.6  104.2  6.2  5.2
# 0.7  104.9  6.9  5.9
# 0.8  105.6  7.6  6.6
# 0.9  106.3  8.3  7.3

Example 4: Calculating the Percentiles of the Columns in a pandas DataFrame

print(my_df.quantile(np.arange(0.01, 1, 0.01)))      # Computing the percentiles of all columns
#            A     B     C
# 0.01  100.07  1.14  1.07
# 0.02  100.14  1.28  1.14
# 0.03  100.21  1.42  1.21
# 0.04  100.28  1.56  1.28
# 0.05  100.35  1.70  1.35
#      ...   ...   ...
# 0.95  106.65  8.65  7.65
# 0.96  106.72  8.72  7.72
# 0.97  106.79  8.79  7.79
# 0.98  106.86  8.86  7.86
# 0.99  106.93  8.93  7.93
#
# [99 rows x 3 columns]

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