Home > database >  How to make a boolean array by checking if the items in an array is in a list?
How to make a boolean array by checking if the items in an array is in a list?

Time:04-25

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.

CodePudding user response:

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])

CodePudding user response:

You can iterate over lst and still use numpy's indexing.

for element in lst:
  arr[arr == element] = 0

CodePudding user response:

You can use this one also.

arr = (1, 2, 3, 4, 5)
lst = [2, 4, 6, 8]

new_arr = tuple('Replace With Anything' if a in lst else a for a in arr)
print(new_arr)
  • Related