NumPy: Compute the 80th percentile for all elements in a given array along the second axis
NumPy Statistics: Exercise-4 with Solution
Write a NumPy program to compute the 80th percentile for all elements in a given array along the second axis.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating a 2x6 array 'x' using arange and reshape
x = np.arange(12).reshape((2, 6))
# Displaying the original array 'x'
print("\nOriginal array:")
print(x)
# Calculating the 80th percentile along the second axis using np.percentile()
r1 = np.percentile(x, 80, 1)
# Displaying the 80th percentile for all elements along the second axis of the array 'x'
print("\n80th percentile for all elements of the said array along the second axis:")
print(r1)
Sample Output:
Original array: [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11]] 80th percentile for all elements of the said array along the second axis: [ 4. 10.]
Explanation:
In the above code –
np.percentile(x, 80, 1): In this code the first argument x is the input array. The second argument 80 is the percentile to compute, i.e., the value below which 80% of the data falls. The third argument 1 specifies that the operation is performed along axis 1, i.e., each row of the array.
r1 = np.percentile(x, 80, 1): This code calculates the 80th percentile of x along the second axis (axis=1), which means the percentiles will be calculated for each row of the array. The resulting array will have the same shape as x but with the second dimension reduced to one.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to calculate the difference between the maximum and the minimum values of a given array along the second axis.
Next: Write a NumPy program to compute the median of flattened given 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://www.w3resource.com/python-exercises/numpy/python-numpy-stat-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics