我有一个二维NumPy数组,例如:
array([[1, 1, 0, 2, 2],
[1, 1, 0, 2, 0],
[0, 0, 0, 0, 0],
[3, 3, 0, 4, 4],
[3, 3, 0, 4, 4]])
我想从该数组中获得某个列表中的所有元素,例如(1、3、4)。在示例情况下,期望的结果将是:
array([[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 3, 0, 4, 4],
[3, 3, 0, 4, 4]])
我知道我可以做(按照这里的建议Numpy:在range内找到元素):
np.logical_or(
np.logical_or(cc_labeled == 1, cc_labeled == 3),
cc_labeled == 4
)
,但这仅在示例情况下有效。实际上,迭代地使用for循环和numpy.logical_or真的很慢,因为可能值的列表以数千为单位(而numpy数组的尺寸大约为1000 x 1000)。
您可以使用np.in1d
-
A*np.in1d(A,[1,3,4]).reshape(A.shape)
另外,np.where
可以使用-
np.where(np.in1d(A,[1,3,4]).reshape(A.shape),A,0)
您还可以np.searchsorted
通过将其可选'side'
参数与输入as一起使用来查找此类匹配项left
,right
并注意对于匹配项,searchsorted将使用这两个输入输出不同的结果。因此,等价于np.in1d(A,[1,3,4])
-
M = np.searchsorted([1,3,4],A.ravel(),'left') != \
np.searchsorted([1,3,4],A.ravel(),'right')
因此,最终输出将是-
out = A*M.reshape(A.shape)
请注意,如果输入搜索列表未排序,则需要使用可选参数sorter
及其argsort
在中的索引np.searchsorted
。
样品运行-
In [321]: A
Out[321]:
array([[1, 1, 0, 2, 2],
[1, 1, 0, 2, 0],
[0, 0, 0, 0, 0],
[3, 3, 0, 4, 4],
[3, 3, 0, 4, 4]])
In [322]: A*np.in1d(A,[1,3,4]).reshape(A.shape)
Out[322]:
array([[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 3, 0, 4, 4],
[3, 3, 0, 4, 4]])
In [323]: np.where(np.in1d(A,[1,3,4]).reshape(A.shape),A,0)
Out[323]:
array([[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 3, 0, 4, 4],
[3, 3, 0, 4, 4]])
In [324]: M = np.searchsorted([1,3,4],A.ravel(),'left') != \
...: np.searchsorted([1,3,4],A.ravel(),'right')
...: A*M.reshape(A.shape)
...:
Out[324]:
array([[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 3, 0, 4, 4],
[3, 3, 0, 4, 4]])
运行时测试和验证输出-
In [309]: # Inputs
...: A = np.random.randint(0,1000,(400,500))
...: lst = np.sort(np.random.randint(0,1000,(100))).tolist()
...:
...: def func1(A,lst):
...: return A*np.in1d(A,lst).reshape(A.shape)
...:
...: def func2(A,lst):
...: return np.where(np.in1d(A,lst).reshape(A.shape),A,0)
...:
...: def func3(A,lst):
...: mask = np.searchsorted(lst,A.ravel(),'left') != \
...: np.searchsorted(lst,A.ravel(),'right')
...: return A*mask.reshape(A.shape)
...:
In [310]: np.allclose(func1(A,lst),func2(A,lst))
Out[310]: True
In [311]: np.allclose(func1(A,lst),func3(A,lst))
Out[311]: True
In [312]: %timeit func1(A,lst)
10 loops, best of 3: 30.9 ms per loop
In [313]: %timeit func2(A,lst)
10 loops, best of 3: 30.9 ms per loop
In [314]: %timeit func3(A,lst)
10 loops, best of 3: 28.6 ms per loop
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句