pythonsortingnumpyrankingarcpy

Rank values in a 2D array, preserve array shape and indices


I want to take a 2D array and then create a new 2D ranked array with the values from lowest to highest, and the same shape and indices.

I am using a numpy array of values for elevation. Below is how far I got with the code, but it is not generating what I want!

import arcpy
import numpy

array = arcpy.RasterToNumPyArray(r"C:\Current\SedMod\SedModv3\TestModel.gdb\Smallprepfin_Clip")

order = array.argsort()
ranks = order.argsort()

print ranks

Clarification: I want to sort all the values contained within the array from the highest value to the lowest value, but maintain the indices and shape of the array.

i.e the highest value(elevation) would be rank 1 and the lowest rank 100 if there are 100 values!


Solution

  • 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.