In this article we will discuss how to find index of a value in a Numpy array (both 1D & 2D) using numpy.where().

Let’s create a Numpy array from a list of numbers i.e.

Now let’s see how to to search elements in this Numpy array.

Find index of a value in 1D Numpy array

In the above numpy array element with value 15 occurs at different places let’s find all it’s indices i.e.

Output:

result is a tuple of arrays (one for each axis) containing the indices where value 15 exists in array arr i.e.

As our array arr is a flat 1D array, so returned tuple will contain only one array of indices and contents of the returned array result[0] are,

Get the first index of element with value 15,

How did it worked ?

numpy.where() accepts a condition and 2 optional arrays i.e.

If only condition argument is given then it returns the indices of the elements which are TRUE in bool numpy array returned by condition. For example following condition,

returns a bool numpy array boolArr, containing TRUE of each element that is equal to 15, for other elements it contains False i.e.

Now if you will pass this bool numpy array to numpy.where()

Then it will return a tuple of arrays (one for each axis) containing indices where value was TRUE in given bool numpy array i.e.

If element not found in numpy array

If the given element doesn’t exist in numpy array then returned array of indices will be empty i.e.

Output:

Find index of a value in 2D Numpy array | Matrix

Let’s create a 2D numpy array i.e.

Contents of the 2D numpy array are,

Let’s find the indices of element with value 15 in this 2D numpy array i.e.

Output:

It returns a tuple of arrays one for each dimension. Like in our case it’s a two dimension array, so numpy.where() will returns a tuple of two arrays.

Now returned array 1 represents the row indices where this value is found i.e.

Whereas, array 2 represents the column indices where this value is found i.e.

Length of both the arrays will be same. So to get the list of exact coordinates we can zip these arrays i.e.

Now let’s iterate over the list of coordinates and print them i.e.

Coordinates of 2d Numpy array where element with value exist i.e.

Get indices of elements based on multiple conditions

When can also pass multiple conditions to numpy.where().
For example, get the indices of elements with value less than 16 and greater than 12 i.e.

Output:

Get the first index of an element in numpy array

Output

Complete example is as follows,

Output:

 

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.