Home > database >  How to remove specific elements in a numpy array (passing a list of values not indexes)
How to remove specific elements in a numpy array (passing a list of values not indexes)

Time:10-29

I have a 1d numpy array and a list of values to remove (not indexes), how can I modify this code so that the actual values not indexes are removed

import numpy as np

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
values_to_remove = [2, 3, 6]

new_a = np.delete(a, values_to_remove)

So what I want to delete is the values 2,3,6 NOT their corresponding index. Actually the list is quite long so ideally I should be able to pass the second parameter as a list

So the final array should actually be = 1, 4, 5, 7, 8, 9

CodePudding user response:

You can use numpy.isin

If you don't mind a copy:

out = a[~np.isin(a, values_to_remove)]

Output: array([1, 4, 5, 7, 8, 9])

To update in place:

np.delete(a, np.isin(a, values_to_remove))

updated a: array([1, 4, 5, 7, 8, 9])

Intermediate:

np.isin(a, values_to_remove)
# array([False,  True,  True, False, False,  True, False, False, False])

CodePudding user response:

You can use numpy.isin.

m = np.isin(a, values_to_remove)
# m -> array([False,  True,  True, False, False,  True, False, False, False])
# ---------  ^^^1 is not in [2, 3, 6]------------ ^^6 is in [2, 3, 6]
print(a[~m])

Output:

array([1, 4, 5, 7, 8, 9])

CodePudding user response:

Use this:

import numpy as np    

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
values_to_remove = [2, 3, 6]

for i in range(0, len(values_to_remove)):
     index = np.where(a==values_to_remove[i])
     a = np.delete(a, index[0][0])

print(a)

Output:

[1 4 5 7 8 9]
  • Related