我有一个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]然而,它看起来有点麻烦,我想知道是否有更好的方法?
发布于 2014-02-19 17:00:47
使用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)]发布于 2014-08-13 15:59:34
使用np.transpose优于zip,对于大型数组来说更快
import numpy as np
myarray = np.random.randint(0, 7, size=1000000)
%timeit indices = zip(*np.where(myarray == 0))
%timeit indices = np.transpose(np.where(myarray == 0))
10 loops, best of 3: 31.8 ms per loop
100 loops, best of 3: 15.9 ms per loophttps://stackoverflow.com/questions/21887138
复制相似问题