2

I wanted to convert the specified elements of the NumPy array A: 1, 5, and 8 into 0.

So I did the following:

import numpy as np

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

bad_values = (A==1)|(A==5)|(A==8)

A[bad_values] = 0

print A

Yes, I got the expected result, i.e., new array.

However, in my real world problem, the given array (A) is very large and is also 2-dimensional, and the number of bad_values to be converted into 0 are also too many. So, I tried the following way of doing that:

bads = [1,5,8] # Suppose they are the values to be converted into 0

bad_values = A == x for x in bads  # HERE is the problem I am facing

How can I do this?

Then, of course the remaining is the same as before.

A[bad_values] = 0

print A

1 Answer 1

4

If you want to get the index of where a bad value occurs in your array A, you could use in1d to find out which values are in bads:

>>> np.in1d(A, bads)
array([ True, False, False, False,  True, False, False,  True, False, False], dtype=bool)

So you can just write A[np.in1d(A, bads)] = 0 to set the bad values of A to 0.

EDIT: If your array is 2D, one way would be to use the in1d method and then reshape:

>>> B = np.arange(9).reshape(3, 3)
>>> B
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

>>> np.in1d(B, bads).reshape(3, 3)
array([[False,  True, False],
       [False, False,  True],
       [False, False,  True]], dtype=bool)

So you could do the following:

>>> B[np.in1d(B, bads).reshape(3, 3)] = 0
>>> B
array([[0, 0, 2],
       [3, 4, 0],
       [6, 7, 0]])
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Sorry I forget to mention that my REAL array A is two dimensional. Is your solution still okay?
Thank you so much. Accepted. Would up vote if I had >15 points.
No problem at all! Glad you found the answer helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.