The NumPy module provides a function numpy.where() for selecting elements based on a condition. It returns elements chosen from a or b depending on the condition.
For example, if all arguments -> condition, a & b are passed in numpy.where() then it will return elements selected from a & b depending on values in bool array yielded by the condition.
If only the condition is provided, this function is a shorthand to the function np.asarray (condition).nonzero(). Although nonzero should be preferred directly, as it behaves correctly for subclasses.
numpy.where(condition[, x, y])
These are the following parameters in numpy.where() function:
condition: array_like, bool
If this parameter set to True, yield x otherwise yield y.
x, y: array_like:
This parameter defines the values from which to choose. The x, y, and condition need to be broadcastable to some shape.
This function returns the array with elements from x where the condition is True and elements from y elsewhere.
import numpy as np a=np.arange(12) b=np.where(a<6,a,5*a) b
In the above code
In the output, the values ranging from 0 to 5 remain the same as per the condition, and the other values have been multiplied with 5.
Output:
import numpy as np a=np.arange(12) b=np.where([[True, False], [True, True]],[[1, 2], [3, 4]],[[9, 8], [7, 6]]) b
Output:
import numpy as np x, y = np.ogrid[:3, :4] a=np.where(x > y, x, 10 + y) a
Output:
In the above code
In the output, the x value has been compared to y value if it satisfied the condition, then it will be printed x value otherwise, it will print y value, which has passed as an argument in the where() function.
x=np.array([[0,1,2],[0,2,5],[0,4,8]]) y=np.where(x<4,x,-2) y
Output: