Coding Ref

How to use numpy.percentile() in Python

How to use numpy.percentile() in Python

numpy.percentile() is a function in the NumPy library in Python that is used to calculate the nth percentile of the elements in an array.

Syntax

The syntax for the numpy.percentile() function is as follows:

main.py
numpy.percentile(a, q, axis=None, out=None, overwrite_input=False, interpolation='linear', keepdims=False)
  • a is the input array
  • q is the percentile to compute
  • axis specifies the axis along which the percentile is to be calculated

The other arguments are optional and are used to specify how the function should behave in certain cases. The function returns the nth percentile of the elements in the input array.

Examples

Here are a two examples of how to use the numpy.percentile() function in Python:

Example 1: Calculate the 25th percentile of an array

We calculate the 25th percentile of an array using the default interpolation method (linear).

main.py
import numpy as np

# Calculate the 25th percentile of an array
array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
percentile = np.percentile(array, 25)
print(percentile)
output
3.25

Example 2: Calculate the 25th percentile of an array along the specified axis

We calculate the 25th percentile of the array along a specified axis.

main.py
import numpy as np

# Calculate the 25th percentile of an array
array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
percentile = np.percentile(array, 25, axis=1)
print(percentile)
output
[1.5 4.5 7.5]

You'll also like

Related tutorials curated for you

    How to use numpy.zeros() in Python

    NumPy: np.arrange()

    How to use numpy.percentile() in Python

    How to use numpy.ravel() in Python

    How to use numpy.linspace() in Python

    How to use numpy.ndarray.flatten() in Python

    How to use numpy.round() in Python

    ModuleNotFoundError: No module named 'numpy' in Python

    How to use numpy.exp() in Python

    How to use numpy.vstack() in Python

    How to use numpy.clip() in Python

    What does numpy.arrange() do?