You can use np.in1d -
A*np.in1d(A,[1,3,4]).reshape(A.shape)
Alternatively, np.where can be used -
np.where(np.in1d(A,[1,3,4]).reshape(A.shape),A,0)
You can also use np.searchsorted to find matches by using the optional 'side' argument with inputs like left and right and noting that for matches, search sorts would produce different results with these two inputs. So the equivalent of np.in1d(A,[1,3,4]) would be -
M = np.searchsorted([1,3,4],A.ravel(),'left') != \ np.searchsorted([1,3,4],A.ravel(),'right')
So the end result will be -
out = A*M.reshape(A.shape)
Note that if the input search list is not sorted, you need to use the optional sorter argument with its argsort indices in np.searchsorted .
Run Example -
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]])
Run-time and exit checks -
In [309]: