numpy.where
numpy.where(condition[, x, y])
This function returns x if the condition is true else it returns y
Example 1: Given a one-dimensional array from (0,9) if elements are less than 5 the element should be the same else multiply the element by 10.
import numpy as np
a = np.arange(10)
np.where(a < 5,a,10*a)
Out[1]: array([ 0, 1, 2, 3, 4, 50, 60, 70, 80, 90])
**Example 2: **Given two 2-D arrays obtain an array with respect to condition.
np.where([[True,False],[True,False]],[[1,2],[3,4]],[[45,52],[78,96]])
Out[3]:
array([[ 1, 52],
[ 3, 96]])
If the condition is true we take element from x else from y.
**Example 3: **given a 2-d matrix if the value in the ix if less than 4, The value should be the same else return the value as -1.
np.where(a < 4,a,-1)
Out[8]:
array([[ 0, 1, 2],
[ 0, 2, -1],
[ 0, 3, -1]])
#machine-learning #artificial-intelligence #python #numpy #matrix