Python Numpy Where

In [1]:
import numpy as np

Let us create an array in numpy

In [5]:
n = np.array([10,11,12,14])

np.where

np.where(condition, x, y)

Above syntax means, if condition is true, output is x otherwise y.

In [18]:
np.where(n < 11, 1, 0)
Out[18]:
array([1, 0, 0, 0])

As we see, only number 10 is less than 11 and thats why we got first 1 and rest all zeros.

np.where Muptiple conditions

In [21]:
np.where((n >11) & (n <14),1,0)
Out[21]:
array([0, 0, 1, 0])

replace values in numpy array using np.where

In [23]:
n1 = np.arange(8)
In [24]:
n1
Out[24]:
array([0, 1, 2, 3, 4, 5, 6, 7])

Let us replace the values less than 4 by -1.

In [28]:
np.where(n1 < 4,-1,n1)
Out[28]:
array([-1, -1, -1, -1,  4,  5,  6,  7])

Above command means if number is less than 4, replace it by -1 otherwise keep it same.

np.where Matrix

np.where can be used on Matrix too.

In [32]:
n2 = np.arange(9).reshape(3,3)
In [33]:
n2
Out[33]:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In [36]:
np.where(n2 < 7,0,n2)
Out[36]:
array([[0, 0, 0],
       [0, 0, 0],
       [0, 7, 8]])

Above command makes everything 0 if number is less than 7.

np.where multiple conditions on Matrix

In [42]:
n2
Out[42]:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In [44]:
np.where((n2 >4) & (n2 < 8),0,n2)
Out[44]:
array([[0, 1, 2],
       [3, 4, 0],
       [0, 0, 8]])

All the values between 4 and 8 are 0.

Without the condition, np.where returns indices of places where the condition is true.

In [83]:
np.where((n2 >4) & (n2 < 8))
Out[83]:
(array([1, 2, 2]), array([2, 0, 1]))

The above result means, value at index 1,2 (row1, col2) which is 5 satisfies the condition. Similarly values at other places 2,2 and 2,1 also satisfy the conditon.