| by Arround The Web | No comments

NumPy np.quantile()

As the name suggests, the quantile() function in NumPy allows you to calculate the qth quantile of the specified array along a set axis. When working with normal distributions, quantiles and percentiles are very fundamental concepts.

Let us explore NumPy’s quantile function.

Function Syntax

The function syntax is as shown below:

numpy.quantile(a, q, axis=None, out=None, overwrite_input=False, method='linear', keepdims=False, *, interpolation=None)

Function Parameters

The function accepts the parameters as follows:

  1. a – the input array or array_like object.
  2. q – your target quantile to calculate. You can also pass an inclusive sequence of quantiles ranging from 0 to 1.
  3. axis – defines along which axis to calculate the quantile. By default, this value is set to None. Hence, the function will flatten the array and calculate the specified quantile.
  4. out – sets an output array for the result.
  5. overwrite_input – this parameter allows the function to modify the input array.
  6. method – specifies the method used in estimating the quantile. Check the docs to discover the accepted values.

Function Return Value

The function returns the qth quantile of the specified array along the set axis.

Example #1

The example shown below calculates a single quantile of a specified array.

# import numpy
import numpy as np
arr = np.array([10,20,30,40,50])
print(f".5 quantile: {np.quantile(arr, 0.5)}")

The code above should return the .5 quantile of the values in the provided array. The resulting output is:

.5 quantile: 30.0

Example #2

To calculate multiple quantiles of a given array, we can do:

arr = np.array([10,20,30,40,50])
print(np.quantile(arr, [0.25, 0.25, 0.50]))

The above code calculates the quantiles as specified in the sequence.

The resulting values are as shown below:

[20. 20. 30.]

Example #3

To calculate the quantile of a 2D array along a specific axis:

arr = np.array([[9,5,3], [4,7,1]])
print(np.quantile(arr, .25, axis=0))

For example, we calculate the .25th quantile along axis 0 of the input array in the code above.

The output is as shown:

[5.25 5.5  1.5 ]

Example #4

You can also change the interpolation method as shown in the example below:

arr = np.array([[9,5,3], [4,7,1]])
print(np.quantile(arr, .25, axis=0, interpolation='nearest'))

This results in the following array:

[4 5 1]

Conclusion

Using this article, you should be familiar with the NumPy quantile function and how to use it to calculate the qth quantiles of a given array along a specified axis.

See you at the next one!!!

Share Button

Source: linuxhint.com

Leave a Reply