# Python Numpy Where

In :
import numpy as np


Let us create an array in numpy

In :
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 :
np.where(n < 11, 1, 0)

Out:
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 :
np.where((n >11) & (n <14),1,0)

Out:
array([0, 0, 1, 0])

## replace values in numpy array using np.where

In :
n1 = np.arange(8)

In :
n1

Out:
array([0, 1, 2, 3, 4, 5, 6, 7])

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

In :
np.where(n1 < 4,-1,n1)

Out:
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 :
n2 = np.arange(9).reshape(3,3)

In :
n2

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

Out:
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 :
n2

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

Out:
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 :
np.where((n2 >4) & (n2 < 8))

Out:
(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.