Ziva
Ziva

Reputation: 3501

Simultaneous changing of python numpy array elements

I have a vector of integers from range [0,3], for example:

v = [0,0,1,2,1,3, 0,3,0,2,1,1,0,2,0,3,2,1].

I know that I can replace a specific values of elements in the vector by other value using the following

v[v == 0] = 5

which changes all appearences of 0 in vector v to value 5. But I would like to do something a little bit different - I want to change all values of 0 (let's call them target values) to 1, and all values different from 0 to 0, thus I want to obtain the following:

v = [1,1,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0]

However, I cannot call the substitution code (which I used above) as follows:

v[v==0] = 1
v[v!=0] = 0

because this obviously leeds to a vector of zeros. Is it possible to do the above substitution in a parralel way, to obtain the desired vector? (I want to have a universal technique, which will allow me to use it even if I will change what is my target value). Any suggestions will be very helpful!

Upvotes: 0

Views: 306

Answers (1)

akuiper
akuiper

Reputation: 215047

You can check if v is equal to zero and then convert the boolean array to int, and so if the original value is zero, the boolean is true and converts to 1, otherwise 0:

v = np.array([0,0,1,2,1,3, 0,3,0,2,1,1,0,2,0,3,2,1])
(v == 0).astype(int)
# array([1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0])

Or use numpy.where:

np.where(v == 0, 1, 0)
# array([1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0])

Upvotes: 1

Related Questions