Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does NumPy have an inverse of unravel_index()?

Tags:

python

numpy

numpy.unravel_index() takes a shape and a flat index into an array, and returns the tuple that represents that index in the array. Is there an inverse? I can compute it by hand, but this seems like it must be a built-in function somewhere...

like image 529
D0SBoots Avatar asked Nov 06 '10 18:11

D0SBoots


People also ask

What is NumPy Unravel_index?

numpy. unravel_index(indices, shape, order='C') Converts a flat index or array of flat indices into a tuple of coordinate arrays. Parameters indicesarray_like. An integer array whose elements are indices into the flattened version of an array of dimensions shape .

Can you index a NumPy array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you find the maximum index of a matrix in python?

To find the index of max value for a specific axis, specify the `axis` keyword argument in [`np. argmax(a, axis=None)`](kite-sym:numpy. argmax). This returns a [`NumPy`](kite-sym:numpy) array with the indices of the max values of each row or column.


2 Answers

Since numpy 1.6.0 (May 2011) there is a built-in NumPy function ravel_multi_index

Converts a tuple of index arrays into an array of flat indices, applying boundary modes to the multi-index.

(This is also mentioned in a comment by user Bi Rico but should really appear as an answer)

like image 118
YXD Avatar answered Sep 23 '22 10:09

YXD


This works:

def ravel_index(pos, shape):
    res = 0
    acc = 1
    for pi, si in zip(reversed(pos), reversed(shape)):
        res += pi * acc
        acc *= si
    return res
like image 26
luispedro Avatar answered Sep 25 '22 10:09

luispedro