您可以使用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)
您也可以通过使用其可选'side'
参数与输入作为left
,并使用np.searchsorted
找到这样的匹配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
我与np.where(...)一起使用,因为它是最直观的理解。谢谢! –