1

For example, I have a numpy array a = np.arange(10), and I need to assign the values in ignore = [2,3,4] to be number 255, like this:

a = np.arange(10)
ignore_value = [3,4,5]
a[a in ignore_value] = 255 # what is the correct way to implement this?

The last line in the program above cannot be accepted by Python3.5 but it shows what I want to do.

Edit:

I found a solution, but it's not vectorized.

for el in ignore_value:
    a[a == el] = 255

This looks really ugly and is very slow since there is a for loop here, so do I have a better way ?

2
  • Just to be clear, you want to select elements by value, not by index? The desired result is [0,1,2,255,255,255,6,7,8,9]? Commented Nov 30, 2018 at 6:06
  • Yes, by value, not index Commented Nov 30, 2018 at 6:33

2 Answers 2

1
In [500]: a = np.arange(10)
In [501]: ignore_value = [3,4,5]
In [502]: np.isin(a, ignore_value)
Out[502]: 
array([False, False, False,  True,  True,  True, False, False, False,
       False])
In [503]: a[np.isin(a, ignore_value)]=255
In [504]: a
Out[504]: array([  0,   1,   2, 255, 255, 255,   6,   7,   8,   9])

You could also construct the mask with:

In [506]: a[:,None]==ignore_value
Out[506]: 
array([[False, False, False],
       [False, False, False],
       [False, False, False],
       [ True, False, False],
       [False,  True, False],
       [False, False,  True],
       [False, False, False],
       [False, False, False],
       [False, False, False],
       [False, False, False]])
In [507]: (a[:,None]==ignore_value).any(axis=1)
Out[507]: 
array([False, False, False,  True,  True,  True, False, False, False,
       False])
Sign up to request clarification or add additional context in comments.

Comments

1

You can use numpy.isin with boolean indexing.

>>> a = np.arange(10)
>>> ignore_value = [3,4,5]
>>> a[np.isin(a, ignore_value)] = 255
>>> a
array([  0,   1,   2, 255, 255, 255,   6,   7,   8,   9])

... or with numpy.where:

>>> a = np.arange(10)
>>> a = np.where(np.isin(a, ignore_value), 255, a)
>>> a
array([  0,   1,   2, 255, 255, 255,   6,   7,   8,   9])

In both cases, np.isin(a, ignore_value) will give you a boolean array indicating where a has a value occuring in ignore_value.

>>> np.isin(a, ignore_value)
array([False, False, False,  True,  True,  True, False, False, False, False])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.