NumPy: Calculate percentiles for a sequence or single-dimensional NumPy array
NumPy: Array Object Exercise-107 with Solution
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.
Python-Numpy Code Editor:
Previous: Write a NumPy program to count the occurrence of a specified item in a given NumPy array.
Next: Write a NumPy program to convert a PIL Image into a numpy array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-107.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics