w3resource

NumPy: Compute the 80th percentile for all elements in a given array along the second axis


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: