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.
import numpy as np # Create a numpy array from a list of numbers arr = np.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17])
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.
# Get the index of elements with value 15 result = np.where(arr == 15) print('Tuple of arrays returned : ', result) print("Elements with value 15 exists at following indices", result[0], sep='\n')
Output:
Tuple of arrays returned : (array([ 4, 7, 11], dtype=int32),) Elements with value 15 exists at following indices [ 4 7 11]
result is a tuple of arrays (one for each axis) containing the indices where value 15 exists in array arr i.e.
(array([ 4, 7, 11], dtype=int32),)
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,
[ 4 7 11]
Get the first index of element with value 15,
result[0][0]
How did it worked ?
numpy.where() accepts a condition and 2 optional arrays i.e.
numpy.where(condition[, x, y])
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,
boolArr = (arr == 15)
returns a bool numpy array boolArr, containing TRUE of each element that is equal to 15, for other elements it contains False i.e.
[False False False False True False False True False False False True False False]
Now if you will pass this bool numpy array to numpy.where()
result = numpy.where(boolArr)
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.
[ 4 7 11]
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.
# If given element doesn't exist in the array then it will return an empty array result = np.where(arr == 111) print('Empty Array returned : ', result) print("value 111 exists at following indices", result[0], sep='\n')
Output:
Empty Array returned : (array([], dtype=int32),) value 111 exists at following indices []
Find index of a value in 2D Numpy array  Matrix
Let’s create a 2D numpy array i.e.
# Create a 2D Numpy array from list of lists arr = np.array([[11, 12, 13], [14, 15, 16], [17, 15, 11], [12, 14, 15]])
Contents of the 2D numpy array are,
[[11 12 13] [14 15 16] [17 15 11] [12 14 15]]
Let’s find the indices of element with value 15 in this 2D numpy array i.e.
# Get the index of elements with value 15 result = np.where(arr == 15) print('Tuple of arrays returned : ', result)
Output:
Tuple of arrays returned : (array([1, 2, 3], dtype=int32), array([1, 1, 2], dtype=int32))
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.
[1, 2, 3]
Whereas, array 2 represents the column indices where this value is found i.e.
[1, 1, 2]
Length of both the arrays will be same. So to get the list of exact coordinates we can zip these arrays i.e.
# zip the 2 arrays to get the exact coordinates listOfCoordinates= list(zip(result[0], result[1]))
Now let’s iterate over the list of coordinates and print them i.e.
# iterate over the list of coordinates for cord in listOfCoordinates: print(cord)
Coordinates of 2d Numpy array where element with value exist i.e.
(1, 1) (2, 1) (3, 2)
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.
# Create a numpy array from a list of numbers arr = np.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17]) # Get the index of elements with value less than 16 and greater than 12 result = np.where((arr > 12) & (arr < 16)) print("Elements with value less than 16 and greater than 12 exists at following indices", result, sep='\n')
Output:
Elements with value less than 16 and greater than 12 exists at following indices (array([ 2, 3, 4, 7, 10, 11], dtype=int32),)
Get the first index of an element in numpy array
result = np.where(arr == 15) if len(result) > 0 and len(result[0]) > 0: print('First Index of element with value 15 is ', result[0][0])
Output
First Index of element with value 15 is 4
Complete example is as follows,
import numpy as np def main(): print("*** Find the index of an element in 1D Numpy Array ***") # Create a numpy array from a list of numbers arr = np.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17]) # Get the index of elements with value 15 result = np.where(arr == 15) print('Tuple of arrays returned : ', result) print("Elements with value 15 exists at following indices", result[0], sep='\n') print('First Index of element with value 15 is : ', result[0][0]) # If given element doesn't exist in the array then it will return an empty array result = np.where(arr == 111) print('Empty Array returned : ', result) print("value 111 exists at following indices", result[0], sep='\n') print("*** Find the index of an element in 2D Numpy Array ***") # Create a 2D Numpy array from list of lists arr = np.array([[11, 12, 13], [14, 15, 16], [17, 15, 11], [12, 14, 15]]) print('Contents of 2D Numpy Array', arr, sep='\n') # Get the index of elements with value 17 result = np.where(arr == 15) print('Tuple of arrays returned : ', result) print('List of coordinates where element with value 15 exists in given 2D array : ') # zip the 2 arrays to get the exact coordinates listOfCoordinates = list(zip(result[0], result[1])) # iterate over the list of coordinates for cord in listOfCoordinates: print(cord) print("*** Get the index of an element based on multiple conditions Numpy Array ***") # Create a numpy array from a list of numbers arr = np.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17]) # Get the index of elements with value less than 16 and greater than 12 result = np.where((arr > 12) & (arr < 16)) print("Elements with value less than 16 and greater than 12 exists at following indices", result, sep='\n') print("*** Get the first index of an element in Numpy Array ***") result = np.where(arr == 15) if len(result) > 0 and len(result[0]) > 0: print('First Index of element with value 15 is ', result[0][0]) if __name__ == '__main__': main()
Output:
*** Find the index of an element in 1D Numpy Array *** Tuple of arrays returned : (array([ 4, 7, 11], dtype=int32),) Elements with value 15 exists at following indices [ 4 7 11] First Index of element with value 15 is : 4 Empty Array returned : (array([], dtype=int32),) value 111 exists at following indices [] *** Find the index of an element in 2D Numpy Array *** Contents of 2D Numpy Array [[11 12 13] [14 15 16] [17 15 11] [12 14 15]] Tuple of arrays returned : (array([1, 2, 3], dtype=int32), array([1, 1, 2], dtype=int32)) List of coordinates where element with value 15 exists in given 2D array : (1, 1) (2, 1) (3, 2) *** Get the index of an element based on multiple conditions Numpy Array *** Elements with value less than 16 and greater than 12 exists at following indices (array([ 2, 3, 4, 7, 10, 11], dtype=int32),) *** Get the first index of an element in Numpy Array *** First Index of element with value 15 is 4
Pandas Tutorials Learn Data Analysis with Python

Pandas Tutorial Part #1  Introduction to Data Analysis with Python

Pandas Tutorial Part #2  Basics of Pandas Series

Pandas Tutorial Part #3  Get & Set Series values

Pandas Tutorial Part #4  Attributes & methods of Pandas Series

Pandas Tutorial Part #5  Add or Remove Pandas Series elements

Pandas Tutorial Part #6  Introduction to DataFrame

Pandas Tutorial Part #7  DataFrame.loc[]  Select Rows / Columns by Indexing

Pandas Tutorial Part #8  DataFrame.iloc[]  Select Rows / Columns by Label Names

Pandas Tutorial Part #9  Filter DataFrame Rows

Pandas Tutorial Part #10  Add/Remove DataFrame Rows & Columns

Pandas Tutorial Part #11  DataFrame attributes & methods

Pandas Tutorial Part #12  Handling Missing Data or NaN values

Pandas Tutorial Part #13  Iterate over Rows & Columns of DataFrame

Pandas Tutorial Part #14  Sorting DataFrame by Rows or Columns

Pandas Tutorial Part #15  Merging or Concatenating DataFrames

Pandas Tutorial Part #16  DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most soughtafter professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.
Just wanted to say this page was EXTREMELY helpful for me. I was stuck on a problem for hours and then found exactly what I was looking for here (info about np.where and 2D matrices). Thanks so much!!