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:

conditionWhen 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.


Following are the examples for numpy.where() function.

Example 1:

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]

Example 2:

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]


Please enter your comment!
Please enter your name here