Joh*_*nak 5 python indexing numpy multidimensional-array
我有一个3D数组,用于np.where
查找满足特定条件的元素.输出np.where
是三个1D阵列的元组,每个阵列沿单个轴给出索引.我想迭代这个输出并打印出满足条件的矩阵中每个点的索引.
一种方法是:
indices = np.where(myarray == 0)
for i in range(0, len(indices[0])):
print indices[0][i], indices[1][i], indices[2][i]
Run Code Online (Sandbox Code Playgroud)
然而,它看起来有点麻烦,我想知道是否有更好的方法?
使用 zip
indices = zip(*np.where(myarray == 0))
Run Code Online (Sandbox Code Playgroud)
那你可以做
for i, j, k in indices:
print ...
Run Code Online (Sandbox Code Playgroud)
例如,
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)]
Run Code Online (Sandbox Code Playgroud)
使用np.transpose
over 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 loop
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5047 次 |
最近记录: |