I have a 2-dimensional NumPy array, for example:
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]])
I would like to get all elements from that array which are in a certain list, for example (1, 3, 4). The desired result in the example case would be:
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]])
I know that I can just do (as recommended here Numpy: find elements within range):
np.logical_or(
np.logical_or(cc_labeled == 1, cc_labeled == 3),
cc_labeled == 4
)
, but this will be only reasonably effective in the example case. In reality iteratively using for loop and numpy.logical_or turned out to be really slow since the list of possible values is in thousands (and numpy array has approximately the dimension of 1000 x 1000).
Use
np.in1d
:in1d
, as the name suggest, operates on the flattened array, therefor you need to reshape after the operation.You can use
np.in1d
-Also,
np.where
could be used -You can also use
np.searchsorted
to find such matches by using its optional'side'
argument with inputs asleft
andright
and noting that for the matches, the searchsorted would output different results with these two inputs. Thus, an equivalent ofnp.in1d(A,[1,3,4])
would be -Thus, the final output would be -
Please note that if the input search list is not sorted, you need to use the optional argument
sorter
with itsargsort
indices innp.searchsorted
.Sample run -
Runtime tests and verify outputs -