Compute q-th percentile using NumPy percentile() method in Python

In this tutorial, we will learn how to compute q-th percentile using NumPy percentile() method in Python.

q-th percentile

The q-th percentile gives a value below which q percentage of the values fall. For example, the 10th percentile gives a value below which 10% of the values fall.

NumPy percentile() method

The NumPy percentile() method is used to compute the q-th percentile of the data along the specified axis.

Syntax:

numpy.percentile (a, q, axis = None, out = None, overwrite_input = False, interpolation = ‘linear’, keepdims = False)

a: data convertible to array on which percentiles are to be computed.
q: percentile/sequence of percentiles to compute.

These two parameters are mandatory while the rest are optional.

This method returns the q-th percentile(s) of the given data.

q-th percentile using NumPy percentile() method in Python

Example 1: Computing a single percentile on 1-Dimensional data

import numpy as np
a = [58, 21, 18, 42, 36]
val = np.percentile (a, 30)
print ("The 30th percentile of a is ",val)

Output:

The 30th percentile of a is  24.0

This means that 30% of values fall below 24.

Example 2: Computing a sequence of percentiles on 1-Dimensional data

import numpy as np
a = [12, 3, 58, 21, 18, 42, 36, 89, 90]
val = np.percentile (a, [12, 32, 56, 81])
print ("The 12th, 32nd, 56th, 81st percentiles of a are ",val)

Output:

The 12th, 32nd, 56th, 81st percentiles of a are  [11.64 19.68 38.88 72.88]

This means that 12%, 32%, 56% and 81% of values fall below 11.64, 19.68, 38.88 and 72.88 respectively.

Example 3: Computing a sequence of percentiles on 2-Dimensional data

import numpy as np
a = [[12, 3, 58, 21],[18, 42, 36, 89]]
val = np.percentile (a, [12, 56])
print ("The 12th, 56th percentiles of a are ",val)

Output:

The 12th, 56th percentiles of a are  [10.56 34.8 ]

Here, the percentile is computed on the entire 2D array.

Example 4: Computing percentile along the specified axis

import numpy as np
a = [[12, 3, 58, 21],[18, 42, 36, 89]]
val1 = np.percentile (a, 56, 0) # axis = 0 for colomn
print ("The 56th percentiles of a along the column are ",val1)
val2 = np.percentile (a, 56, 1) # axis = 1 for row
print ("The 56th percentiles of a along the row are ",val2)

The 2D array we created is:
Compute q-th percentile using NumPy percentile() method in Python

Use the axis parameter to specify along which axis percentile should be computed. Set axis=0 to compute along the column and axis=1 to compute along the row.

Output:

The 56th percentiles of a along the column are  [15.36 24.84 48.32 59.08]
The 56th percentiles of a along the row are  [18.12 40.08]

You may also read, Join Multiple Lists in Python
Understanding NumPy array dimensions in Python

Leave a Reply