How to calculate percentiles in NumPy?

In this tutorial, we will learn how to calculate percentiles in NumPy? By Pranit Sharma Last updated : May 25, 2023

A percentile is a score (value) that a specific percentage falls at or below. For example, the 21st percentile is the score below which 21% of the score will be found.

We can understand it by another example, let's suppose if you got 91st percentile in any exam, that means you’re above 91% of the students.

Suppose we are given a sequence for a single-dimensional NumPy array and we need to find a convenient way to calculate percentile from this array.

Calculating percentiles in NumPy array

To calculate percentiles in NumPy, you can use numpy.percentile() method which calculates and returns the nth percentile of the given data (NumPy array).

numpy.percentile() Syntax

numpy.percentile(a, q, axis=None, out=None, overwrite_input=False,
     method='linear', keepdims=False, *, interpolation=None)

Let us understand with the help of an example,

Python Programs to Calculate Percentiles in NumPy

Consider the below-given examples to calculate the percentiles with NumPy:

Example 1: Calculate percentiles with NumPy 1D Array

# Import numpy
import numpy as np

# data (NumPy array)
arr = np.array([87, 93, 65, 75, 85, 90])

# Printing array
print("Data (arr):\n",arr,"\n")

# Calculating 50th percentile
res = np.percentile(arr, 50)
print("50th Percentile is:\n",res)

# Calculating 91st percentile
res = np.percentile(arr, 91)
print("91st Percentile is:\n",res)

Output

Data (arr):
 [87 93 65 75 85 90] 

50th Percentile is:
 86.0
91st Percentile is:
 91.65

Example 2: Calculate percentiles with NumPy 2D Array

# Import numpy
import numpy as np

# data (NumPy array)
arr = np.array([[50,60,80],[60,90,20]])

# Printing array
print("Data (arr):\n",arr,"\n")

# Calculating 99th percentile
res = np.percentile(arr, 99)
print("99th Percentile is:\n",res)

# Calculating 93rd percentile
res = np.percentile(arr, 93)
print("93rd Percentile is:\n",res)

Output

Data (arr):
 [[50 60 80]
 [60 90 20]] 

99th Percentile is:
 89.5
93rd Percentile is:
 86.5

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.