How to calculate percentile in Numpy?

Calculating percentiles in Python using NumPy is simple and efficient. Let’s explore how to use the percentile function in the NumPy library.

numpy percentile

Using Numpy percentile function

NumPy provides the percentile function, which allows you to calculate percentiles from a given dataset. A percentile is a measure used in statistics indicating the value below which a given percentage of observations fall.

See also  Multiple Regression with NumPy

Here’s how to calculate percentiles using NumPy:

import numpy as np

a = (1, 5, 7, 11, 87, 45)

print(f"{np.percentile(a, 10)}")
print(f"{np.percentile(a, 45)}")
print(f"{np.percentile(a, 50)}")
print(f"{np.percentile(a, 75)}")
print(f"{np.percentile(a, 95)}")

The percentile function takes two main arguments:

Data Array: The dataset from which you want to calculate the percentile (in this case, a).
Percentile: The desired percentile (e.g., 10, 45, 50, 75, 95).

See also  How to generate Cauchy Matrix from arrays in Numpy?

In this example, the function calculates various percentiles for the dataset a. The 50th percentile, for instance, represents the median of the dataset.

Check also how to calculate percentile in Excel.