Open In App

numpy.quantile() in Python

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

numpy.quantile() function is used to find the qth quantile, which is the value below which a given percentage q of data falls in a NumPy array. For example, it can tell you what value lies at the 25% mark of your data, what the median (50th percentile) is, or what value corresponds to the 90th percentile.

In the figure given above, Q2 is the median of the normally distributed data. Q3 – Q1 represents the Interquartile Range of the given dataset.

Syntax of numpy.quartile()

numpy.quantile(arr, q, axis=None, out=None, keepdims=False)

Parameters:

Parameter

Type

Description

arr

array_like

Input data array.

q

float or array-like

Quantile(s) to compute (range: 0 to 1).

axis

int or tuple of ints, optional

Axis/axes to compute quantiles on. Default flattens the array.

out

ndarray, optional

Output array to store results.

keepdims

bool, optional

If True, keeps reduced dimensions (for broadcasting).


Returns: It returns an ndarray of quantile values. If q is a single value, the result is a scalar (if axis=None) or a 1D array (if axis is specified). For multiple quantiles, returns an array of quantiles computed along the given axis.

Examples of numpy.quantile()

Example 1: In this example, we calculate the quantiles of a 1D array. We find the 25th percentile, the 50th percentile (median) and the 75th percentile of the data.

Python
import numpy as np
a = [20, 2, 7, 1, 34]

print(np.quantile(a, 0.25)) 
print(np.quantile(a, 0.5))
print(np.quantile(a, 0.75))

Output
2.0
7.0
20.0

Example 2: In this example, we calculate the quantiles of a 2D array. We find the median of all elements, the 25th percentile for each column and the median for each row.

Python
import numpy as np

a = np.array([
    [14, 17, 12, 33, 44],
    [15, 6, 27, 8, 19],
    [23, 2, 54, 1, 4]
])

# Median of all elements
print(np.quantile(a, 0.5))

# 25th percentile of each column
print(np.quantile(a, 0.25, axis=0))

# Median of each row
print(np.quantile(a, 0.5, axis=1))

Output
15.0
[14.5  4.  19.5  4.5 11.5]
[17. 15.  4.]

Example 3: In this example, we calculate the 25th and 75th percentiles of a 1D array. This helps us understand the spread of the data between the lower and upper quartiles.

Python
import numpy as np

a = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(np.quantile(a, [0.25, 0.75]))

Output
[30. 70.]

Example 4: In this example, we calculate the 50th percentile (median) of a 1D array and store the result in an existing array res using the out parameter of numpy.quantile().

Python
import numpy as np

a = [10, 20, 30, 40, 50]
res = np.zeros(1)

# Calculate and store 50th percentile
np.quantile(a, 0.5, out=res)

print(res)

Output
[30.]


Next Article

Similar Reads