Introduction
NumPy is a Python library used for working with arrays.NumPy has various functions. Those functions are numpy array functions. One of the function is numpy.where(). It is used to return the indices of elements in an input array where the given condition is satisfied.
Syntax
Return Value of numpy.where()
- If both x and y are specified then it returns elements of x where the condition is True and elements of y where the condition is false.
- If only condition is given, then it returns the tuple of indices of element where condition is true
The exact same circumstance can also be shown as a = 2. Given how difficult it is to write the condition array as a boolean array, this is the format that is advised.
But what if we want to keep the result's dimension while retaining the items of our original array? Numpy.where() is a useful tool for this.
There are two additional variables: x and y. What do those mean?
In essence, this states that the new array will select elements from x if the condition is true for any element in our array.
If it is false, however, elements from y will be taken.
This will result in an array with items from x whenever condition is True and elements from y whenever condition is False in our final output array.
Although x and y are optional, it should be noted that if you specify x, you MUST also specify y. This is due to the requirement that the output array's shape match that of the input array in this situation.
Examples
Example 1
function with condition
Output:
Here the condition is arr>50. So the index of elements where value is greater than 50 is returned as tuple.
Example 2
Condition with x and y value
Output:
Here condition along with x and y values are given which returns an array where condition satisfied index position is indicated by 1 and not satisfied condition with 3.
Example 3
2D array
Output:
Here each element of 2D array is checked for the condition and corresponding x and y value are returned.
Example 4
numpy.where() without condition statement
Output:
Here function returns array according to boolean condition. True will yield element from X array and False will yield element from Y array.
Broadcasting with numpy.where()
Numpy will broadcast every condition, x, and y array that we supply.
Output:
Again, the output is chosen based on the condition in this case, thus all elements are considered, but in this case, b is broadcast to the shape of a. (Since one of its dimensions only has one element, there won't be any mistakes when broadcasting.)
Therefore, b will now be [[0 1 2 3]]. We may now choose elements even from this broadcasted array [0 1 2 3] [0 1 2 3].
As a result, the output's shape matches that of a.