w3resource

NumPy: Calculate percentiles for a sequence or single-dimensional NumPy array


Calculate Percentiles of Array

Write a NumPy program to calculate percentiles for a sequence or single-dimensional NumPy array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'nums' containing integers
nums = np.array([1, 2, 3, 4, 5])

# Printing the 50th percentile (median) of the array 'nums'
print("50th percentile (median):")
p = np.percentile(nums, 50)
print(p)

# Printing the 40th percentile of the array 'nums'
print("40th percentile:")
p = np.percentile(nums, 40)
print(p)

# Printing the 90th percentile of the array 'nums'
print("90th percentile:")
p = np.percentile(nums, 90)
print(p)

Sample Output:

50th percentile (median):
3.0
40th percentile:
2.6
90th percentile:
4.6

Explanation:

In the above code -

nums = np.array([...]): This line creates a NumPy array named 'nums' containing integer values 1 to 5.

p = np.percentile(nums, 50): Calculate the 50th percentile (also known as the median) of the 'nums' array, which is the value that separates the lower 50% from the upper 50% of the data.

p = np.percentile(nums, 40): Calculate the 40th percentile of the 'nums' array, which is the value that separates the lower 40% from the upper 60% of the data.

p = np.percentile(nums, 90): Calculate the 90th percentile of the 'nums' array, which is the value that separates the lower 90% from the upper 10% of the data.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to compute the 25th, 50th, and 75th percentiles of a 1D array using np.percentile.
  • Create a function that takes a percentile value as input and returns the corresponding array element.
  • Test the percentile function on a sorted array and verify the median calculation matches np.median.
  • Implement a solution that calculates percentiles for each column in a 2D array independently.

Go to:


PREV : Count Occurrences of Item in Array
NEXT : Convert PIL Image to NumPy Array


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.