numpy.where() in Python with Examples
numpy.where() function in Python returns the indices of items in the input array when the given condition is satisfied.
Basic Syntax
Following is the basic syntax for np.where() function:
numpy.where(condition[, x, y])
And the parameters are:
Parameter | Description |
---|---|
condition | When condition is true it yields x otherwise y. Where x,y are the values from which to choose x and y |
Return Value
When both x and y is provided then if the condition becomes true it will return elements of x otherwise elements of y.
Example
Following are the examples for numpy.where() function.
Example 1:
# Python program illustrating where() function import numpy as np # items array. items = np.array([[0, 10, 20], [30, 40, 50]]) # print items array print(items) # now print item elements which are greater than 20 print ('All indices of elements >20') result = np.where(items>20) print(result) print("All elements which are >20") print(items[result])
The output should be:
[[ 0 10 20]
[30 40 50]]
All indices of elements >20
(array([1, 1, 1]), array([0, 1, 2]))
All elements which are >20
[30 40 50]
[30 40 50]]
All indices of elements >20
(array([1, 1, 1]), array([0, 1, 2]))
All elements which are >20
[30 40 50]
Example 2:
# Python program illustrating where() function import numpy as np # items array. items = np.arange(4,10).reshape(2,3) # print items array print(items) # now print item elements which are greater than 20 print ('All indices of elements <7') result = np.where(items<7) print(result) print("All elements which are <7") print(items[result])
The output should be:
[[4 5 6]
[7 8 9]]
All indices of elements <7
(array([0, 0, 0]), array([0, 1, 2]))
All elements which are <7
[4 5 6]
[7 8 9]]
All indices of elements <7
(array([0, 0, 0]), array([0, 1, 2]))
All elements which are <7
[4 5 6]
LATEST POSTS
-
Java Math abs() method with examples
-
Binary Search in Java
-
Insertion Sort in Java
-
How to Print Without Newline in Python
-
Java Stack Class Tutorial with Examples
-
Binary Search in C
-
numpy.dot() in Python
-
numpy.append() in Python
-
Read and Write text to files in Python
-
Binary Search in C++
-
Python square root sqrt() method
-
numpy.argmax() in Python