Numpy: convert index in one dimension to many dimensions

Many array methods return a single index, despite the fact that the array is multidimensional. For instance:

a = rand(2,3)
z = a.argmax()

For two dimensions, it is easy to find the matrix indices of the maximum element:

a[z/3, z%3]

But for more measurements, this can be annoying. Does Numpy / Scipy have an easy way to return indexes in multiple dimensions, given the index in one (collapsed) dimension? Thank.

+3
source share
2 answers

Got it!

a = X.argmax()
(i,j) = unravel_index(a, X.shape)
+5
source

I don’t know the built-in function that does what you want, but where is it for me, I realized that I really wanted to do the following:

2 a, b , b, ( [i, j, k...]) a

numpy-ish:

j = a.flatten().argmax()
corresponding_b_element = b.flatten()[j]

+1

Source: https://habr.com/ru/post/1728663/


All Articles