Get all indices of an N-dimensional array as a list

Viewed 229

Is there a way to get a list or array of all indices in an N-dimensional array in a fast and efficient way in Python?

For example, image we have the following array:

import numpy as np

test = np.zeros((4,4))

array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

I would like to get all element indices as follows:

indices = [ [0,0],[0,1],[0,2] ... [3,2],[3,3] ]
5 Answers

Use np.indices with a bit of reshaping:

np.indices(test.shape).reshape(2, -1).T

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

I'd suggest making an array of 1 in the same shape as your test array using np.ones_like, then using np.where:

>>> np.stack(np.where(np.ones_like(test))).T
# Or np.dstack(np.where(np.ones_like(test)))
array([[0, 0],
       [0, 1],
       [0, 2],
       [0, 3],
       [1, 0],
       [1, 1],
       [1, 2],
       [1, 3],
       [2, 0],
       [2, 1],
       [2, 2],
       [2, 3],
       [3, 0],
       [3, 1],
       [3, 2],
       [3, 3]])

If you are fine with using a list comprehension

test = np.zeros((4,4))
indices = [[i, j] for i in range(test.shape[0]) for j in range(test.shape[1])]
print (indices)

[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]

Just enumerate should do:

test = [[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]]

indices = [[i, j] for i, row in enumerate(test) for j, col in enumerate(row)]
print(indices)

>>> [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3], [4, 0], [4, 1], [4, 2], [4, 3]]

You can try itertools.product:

>>> from itertools import product
>>> 
>>> [list(i) for i in product(range(4), range(4))]
[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [3, 0], [3, 1], [3, 2], [3, 3]]
Related