In this article, How to use Python numpy.where() method. This function in Python and how it is used to search data in huge datasets by using some conditions. Before we will see this function’s usage, first let us understand what this function is and how it works, what are the arguments for numpy.where() function take. So let us begin with the syntax.
What is Python numpy.where() Method
numpy. where() methods return a ndarray if x is true and y is false takes one argument in the form of a condition, which takes 2 more arguments(x,y) to help numpy.where function operates.
Syntax of np.where()
numpy.where(condition[, x, y])
Parameters
- condition: if condition is true for some elements of array then new array returns elements of x else if false elements of y will return.The returns array would be Numpy array of bool.
- x, y: It is an Optional parameter,it can Python objects(array, lists, etc.) can be passed.x,y and condition are broadcast to same shape.
Returns
- The np.where() returns ndarray or array_of_tuple : if both x and y are pass condition.The return output array contains elements of x whenever condition is True for x elements else return elements of Y.
- if only condition is passed , then it returns the indices of the elements or tuple condition.nonzero() where condition is TRUE.
- If the array is a multidimensional array then it returns a tuple of arrays with the index of each axis. Using the indices returned, we can access the values of the elements also.
1. How to NumPy.Where() with only Condition
In this example, we will see how to make use of the NumPy.where() function on a NumPy array and evaluate it based on a condition.
Python code Example
import numpy as np
# a is an 1-D array of integers.
a = np.array([1, 2, 3, 4, 5, 6])
b = np.where(a<4)
print ('This is our original array')
print(a)
print ('\nResults of where condition for Indices of elements <4')
print(b)
print("\nActual Elements values which are <4 in original array")
print(a[b])
Output
This is our original array
[1 2 3 4 5 6]
Results of where condition for Indices of elements <4
(array([0, 1, 2], dtype=int32),)
Actual Elements values which are <4 in original array
[1 2 3]
2. NumPy.Where() with only Condition on 2-D array
In this example, we are using the 2D array and filtering element by applying the condition in NumPy.Where() fetching all elements which are less than 4.
Python Program Example
import numpy as np
# a is an 2-D array of integers.
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.where(a<4)
print ('This is our original 2-D array')
print(a)
print ('\n Results of where condition for Indices of elements <4')
print(b)
print("\n Actual Elements values which are <4 in original array")
print(a[b])
Output:
This is our original 2-D array
[[1 2 3]
[4 5 6]]
Results of where condition for Indices of elements <4
(array([0, 0, 0], dtype=int32), array([0, 1, 2], dtype=int32))
Actual Elements values which are <4 in original array
[1 2 3]
3. Numpy.where() without any condition on boolean array
In the above two examples of numpy. were, we used a condition as an argument, and based on the condition results we evaluate the array. But in this example, we are going to see special usage of numpy.where() function in which instead of passing a condition, we will pass the precalculated boolean results in the form of an array.
Then this first array will be used to evaluate x & y arrays that we pass as second and third arguments.
How does it work?
- numpy. where(), it says first this function evaluates the condition, if condition results true then it picks element from x, if condition results false, it picks element from y.To apply this definition to our below above.
- The first condition result is True, so it picked 1 from x array.
- second condition result is False, so it picked 5 from y array.
- The third condition result is False, so again it picked 6 from the y array. This gave us a new array with results as [1 5 6].
Program code Example
import numpy as np
a= np.where([True, False, False],
[1, 2, 3],
[4, 5, 6])
print(a)
Output
[1 5 6]
4. Replace element based on condition
In this example, we are replacing elements that satisfy the condition.
import numpy as np
orignal_array = np.arange(12).reshape((4, 3))
print(f"original array:\n{orignal_array}\n")
print('Replace array :\n',np.where(orignal_array<4,-2, 50))
Output
original array:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
Replace array :
[[-2 -2 -2]
[-2 50 50]
[50 50 50]
[50 50 50]]
Imp Notes: np.where() functon Arguments
- x & y, are array_like, which means both the arrays must be of the same length or shape. numpy.where() uses the concept of NumPy array broadcasting. If you use different size arrays then it will thow error.
- Numpy. where(): function can be called either with single condition argument or will all 3 argumenets which includes condition and x & y. This function can never be called with 2 arguments.
- The condition argument can be passed as a logical condition that results in the boolean results or it can be passed as an array of boolean results. This is a special case where instead of passing the condition we pass the boolean results of the condition in the form of an array. We will cover this case with an example in this article.
Conclusion
In this article, we learned about the definition, arguments, and return values of the NumPy.where() function. np.where() NumPy where Method in Python