Skip to content Skip to sidebar Skip to footer

Rank Values In A 2d Array

Hi basically I want to input a 2D array and then create a new ranked array with the values from lowest to highest. The array I am using is an elevation raster converted to a numpy

Solution 1:

How about something like this:

>>> a
array([[ 0.76303184,  0.17748702,  0.89365504,  0.07221609],
       [ 0.12267359,  0.56999037,  0.42877407,  0.8875015 ],
       [ 0.38178661,  0.57648393,  0.47056551,  0.03178402],
       [ 0.03606595,  0.93597727,  0.02199706,  0.73906879]])
>>> a.ravel().argsort().argsort().reshape(a.shape)
array([[12,  5, 14,  3],
       [ 4,  9,  7, 13],
       [ 6, 10,  8,  1],
       [ 2, 15,  0, 11]])

Not super happy with this, there is likely a better way.

Solution 2:

You need scipy.stats.rankdata for this

from scipy.statsimport rankdata
ranks=rankdata(a).reshape(a.shape)

To rank from highest to lowest, invert the input a

ranks=rankdata(a.max()-a).reshape(a.shape)

Post a Comment for "Rank Values In A 2d Array"