Search code examples
pythonnumpymachine-learningdata-sciencedata-analysis

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?


Solution

  • 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