0

I try iterate over values of a 2d ndarray and get the index as well. Therefor I tried to sort the 2d ndarray. Also tried different things with (arg-)sorting parameters of numpy.

import numpy
arr = numpy.array([[2,11,4], [33,9,5], [3,21,123]])
print(arr.argsort(axis=None)

This returns:

array([0, 6, 2, 5, 4, 1, 7, 3, 8])

But I want to return a list like this where each list element contains the 2-dimensional index like this:

[(0,0), (2,0), (0,2), (1,2), (1,1), (0,1), (2,1), (1,0), (2,2)]

1 Answer 1

2

Using numpy's unravel_index, we can do the following:

import numpy as np
arr = np.array([[2,11,4], [33,9,5], [3,21,123]])
ix, jx = np.unravel_index(arr.argsort(axis=None), arr.shape)
print(list(zip(ix,jx)))

Which outputs

[(0, 0), (2, 0), (0, 2), (1, 2), (1, 1), (0, 1), (2, 1), (1, 0), (2, 2)]

for this example, as requested.

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

1 Comment

Works perfectly for me

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.