1

I want to iterate over a numpy array starting at the index of the highest value working through to the lowest value

import numpy as np #imports numpy package

elevation_array = np.random.rand(5,5) #creates a random array 5 by 5

print elevation_array # prints the array out

ravel_array = np.ravel(elevation_array)
sorted_array_x = np.argsort(ravel_array)
sorted_array_y = np.argsort(sorted_array_x)

sorted_array = sorted_array_y.reshape(elevation_array.shape)

for index, rank in np.ndenumerate(sorted_array):
    print index, rank

I want it to print out:

index of the highest value index of the next highest value index of the next highest value etc

2 Answers 2

3

If you want numpy doing the heavy lifting, you can do something like this:

>>> a = np.random.rand(100, 100)
>>> sort_idx = np.argsort(a, axis=None)
>>> np.column_stack(np.unravel_index(sort_idx[::-1], a.shape))
array([[13, 62],
       [26, 77],
       [81,  4],
       ..., 
       [83, 40],
       [17, 34],
       [54, 91]], dtype=int64)

You first get an index that sorts the whole array, and then convert that flat index into pairs of indices with np.unravel_index. The call to np.column_stack simply joins the two arrays of coordinates into a single one, and could be replaced by the Python zip(*np.unravel_index(sort_idx[::-1], a.shape)) to get a list of tuples instead of an array.

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

from operator import itemgetter

>>> a = np.array([[2, 7], [1, 4]])
array([[2, 7],
       [1, 4]])

>>> sorted(np.ndenumerate(a), key=itemgetter(1), reverse=True)
[((0, 1), 7), 
 ((1, 1), 4), 
 ((0, 0), 2), 
 ((1, 0), 1)]

you can iterate this list if you so wish. Essentially I am telling the function sorted to order the elements of np.ndenumerate(a) according to the key itemgetter(1). This function itemgetter gets the second (index 1) element from the tuples ((0, 1), 7), ((1, 1), 4), ... (i.e the values) generated by np.ndenumerate(a).

2 Comments

Hi elyase and dkar thanks. I was wondering could you explain this a little bit for me? I am still very new to numpy and python.
Thanks elyase thats great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.