Search code examples
pythonarraysnumpynumpy-ndarray

Given a Numpy array, how to calculate the percentile of each of the array elements?


I have an array like this:

import numpy as np

arrx = np.array([0, 5, 10])
print(np.percentile(arrx, 100))

Which returns a single scalar: the element that more closely matches the percentile I specified as a second argument. In this case, 10.

I would like however to get an equivalent array which gives the percentile of each element, for example:

# do something
> [0, 50, 100]

Where the first element is at the 0 percentile, 5 is at 50%, and so forth.

How can this be done efficiently with numpy?

Thanks!


Solution

  • Simply standardize by the max:

    arrx/arrx.max()*100
    

    Or maybe by the min/max:

    (arrx-arrx.min())/(arrx.max()-arrx.min())*100
    

    Output: array([ 0., 50., 100.])