I’m trying to find every item in an numpy array arr
that’s also in an arbitrary list lst
and replace them, but while arr > 0
will generate a boolean array for easy masking, arr in lst
only works with all() or any() which isn’t what I need.
Example input: array (1, 2, 3, 4, 5)
, list [2, 4, 6, 8]
Output: array (1, 0, 3, 0, 5)
I managed to get the same result with for loops:
for i in range(len(arr)): if arr[i] in lst: arr[i] = 0
Just wondering if there are other ways to do it that set arrays apart from lists.
Advertisement
Answer
You can use numpy.isin
:
a = np.array((1, 2, 3, 4, 5)) lst = [2, 4, 6, 8] a[np.isin(a, lst)] = 0
Gives you an a
of:
array([1, 0, 3, 0, 5])