是否有一种方法可以在Python中以快速有效的方式获取N维数组中所有索引的列表或数组?
例如,图像我们具有以下数组:
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.]])
我想获得所有元素索引,如下所示:
indices = [ [0,0],[0,1],[0,2] ... [3,2],[3,3] ]
答案 0 :(得分:3)
使用np.indices
进行一些调整:
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]])
答案 1 :(得分:1)
如果您可以使用列表理解
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]]
答案 2 :(得分:1)
我建议使用1
,然后使用test
,以与您的np.ones_like
数组相同的形状来制作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]])
答案 3 :(得分:1)
只需枚举即可:
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]]
答案 4 :(得分:0)
您可以尝试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]]