tempacc
tempacc

Reputation: 11

np.where condition selects odd elements where the condition specifies to select the even ones

I am trying out an assignment with numpy when I noticed something weird and wasn't able to figure out.

Question: Replace all odd numbers in arr with -1.

Array to replace -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Result -> array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])

I tried the following syntax:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) #What went wrong here?
np.where(arr%2==0,arr,-1)

The output is weirdly array([ 0, -1, 2, -1, 4, -1, 6, -1, 8, -1])

This is exactly what I wanted but notice the where condition? I mistakenly wrote the condition to select even elements but its selecting the odd elements for some reason.

I tried the same thing with argwhere:

arr[np.argwhere((arr%2!=0))] = -1

It gives the expected outcome. So, what went wrong with np.where?

Upvotes: 0

Views: 303

Answers (2)

Venkat
Venkat

Reputation: 115

The first argument in numpy.where (Condition) indicates if it is True, leave the element as it is.

If the condition is false, operate on the element using the 3rd parameter mentioned in the numpy.where. So whatever is the behavior you are experience is correct.

Refer to the example given in Numpy documentation @https://numpy.org/doc/stable/reference/generated/numpy.where.html Also you can refer https://www.journaldev.com/37898/python-numpy-where

Upvotes: 0

dnalow
dnalow

Reputation: 984

Everything behaves as expected. Have a look at the numpy.where docstring. You are choosing those elements of arr where the condition is true, -1 otherwise. Your condition yields True for numbers that are multiples of 2.

Upvotes: 1

Related Questions