遍历`np.where`的输出
问题内容:
我有一个3D数组,用于np.where
查找满足特定条件的元素。的输出np.where
是三个一维数组的元组,每个数组沿一个轴给出索引。我想遍历此输出并打印出矩阵中符合条件的每个点的索引。
一种方法是:
indices = np.where(myarray == 0)
for i in range(0, len(indices[0])):
print indices[0][i], indices[1][i], indices[2][i]
但是,这看起来有点麻烦,我想知道是否有更好的方法?
问题答案:
采用 zip
indices = zip(*np.where(myarray == 0))
那你可以做
for i, j, k in indices:
print ...
例如,
In [1]: x = np.random_integers(0, 1, (3, 3, 3))
In [2]: np.where(x) # you want np.where(x==0)
Out[2]: (array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2]),
array([0, 1, 1, 2, 2, 0, 0, 1, 1, 2]),
array([1, 0, 1, 0, 1, 1, 2, 0, 2, 2]))
In [3]: zip(*np.where(x))
Out[3]: [(0, 0, 1),
(0, 1, 0),
(0, 1, 1),
(0, 2, 0),
(0, 2, 1),
(1, 0, 1),
(1, 0, 2),
(1, 1, 0),
(1, 1, 2),
(2, 2, 2)]