# numpy.where() in Python with examples

In this article, you will learn how numpy.where() method works with examples. The number where () depends on the function element returns either x or y from array_like objects.

Where () is the syntax of the function:

numpy.where (position [, x, y])

Condition: A conditional expression that returns an array of nulls

x, y: Array (optional) Both pass or no pass

If all arguments -> status, x & y are passed to numpy.where (), it will return the selected elements from x & y based on the values in the bool array obtained by the condition.

### Important points:

We can hereto pass all three advocacy or pass only one condition advocacy. If we are going to numpy.where () to pass all three arguments.Then all the three NumPy arrays must be of the same length otherwise it will raise the following error,*ValueError: operands could not be broadcast together with shapes.The NumPy module provides a function numpy.where () for the selection of elements based on a condition. It returns elements based on the condition or chosen from b.*

**CODE IN PYTHON:**

import numpy as np # a is an array of integers. a = np.array([[1, 2, 3], [4, 5, 6]]) print(a) print ('Indices of elements <4') b = np.where(a<4) print(b) print("Elements which are <4") print(a[b])

Output:

[[1 2 3] [4 5 6]] Indices of elements <4 (array([0, 0, 0], dtype=int64), array([0, 1, 2], dtype=int64)) Elements which are <4 array([1, 2, 3])

## Return Value:

When both x and y are provided then if the condition becomes true it will return elements of x otherwise elements of y.

**1) **Numpy.where () with one condition and two array_like variables

2) Numpy.where () with two dimensional array

3) Numpy.where () passed with many conditions

4) Numpy.where () is a function with one dimensional array:

The numpy.where () function returns an array with pointer to pointer where the specified condition is true. The given condition a> 5.Since, a = [6, 2, 9, 1, 8, 4, 6, 4] the index where a>5 is 0,2,4,6.

import numpy as np a = np.random.randint(1,10,8) print(a) #array([6, 2, 9, 1, 8, 4, 6, 4]) w = np.where(a>5) print(w) #(array([0, 2, 4, 6], dtype=int32),)

Output:

[8 5 7 4 2 6 5 3] (array([0, 2, 5], dtype=int64),)

Time complexity : O(1)

*Thanks for visiting codespeedy. I hope it helps you.*

## Leave a Reply

You must be logged in to post a comment.