numpy.unravel_index

numpy.unravel_index(x, dims)

Convert a flat index to an index tuple for an array of given shape.

Parameters :

x : int

Flattened index.

dims : tuple of ints

Input shape, the shape of an array into which indexing is required.

Returns :

idx : tuple of ints

Tuple of the same shape as dims, containing the unraveled index.

Notes

In the Examples section, since arr.flat[x] == arr.max() it may be easier to use flattened indexing than to re-map the index to a tuple.

Examples

>>> arr = np.arange(20).reshape(5, 4)
>>> arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
>>> x = arr.argmax()
>>> x
19
>>> dims = arr.shape
>>> idx = np.unravel_index(x, dims)
>>> idx
(4, 3)
>>> arr[idx] == arr.max()
True

Previous topic

numpy.ogrid

Next topic

numpy.diag_indices

This Page