- NumPy Searching Arrays
- Example
- Example
- Example
- Search Sorted
- Example
- Search From the Right Side
- Example
- Multiple Values
- Example
- Find element in array python numpy
- Universal Functions
- Working With Images
- Projects and Applications with NumPy
- Introduction
- Creating NumPy Array
- NumPy Array Manipulation
- Matrix in NumPy
- Operations on NumPy Array
- Reshaping NumPy Array
- Indexing NumPy Array
- Arithmetic operations on NumPyArray
- Linear Algebra in NumPy Array
- NumPy and Random Data
- Universal Functions
- Working With Images
- Find the index of value in Numpy Array using numpy.where()
- Find index of a value in 1D Numpy array
- Frequently Asked:
- If element not found in numpy array
- Find index of a value in 2D Numpy array | Matrix
- Get indices of elements based on multiple conditions
- Get the first index of an element in numpy array
- Summary
- Related posts:
NumPy Searching Arrays
You can search an array for a certain value, and return the indexes that get a match.
To search an array, use the where() method.
Example
Find the indexes where the value is 4:
arr = np.array([1, 2, 3, 4, 5, 4, 4])
The example above will return a tuple: (array([3, 5, 6],)
Which means that the value 4 is present at index 3, 5, and 6.
Example
Find the indexes where the values are even:
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
Example
Find the indexes where the values are odd:
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
Search Sorted
There is a method called searchsorted() which performs a binary search in the array, and returns the index where the specified value would be inserted to maintain the search order.
The searchsorted() method is assumed to be used on sorted arrays.
Example
Find the indexes where the value 7 should be inserted:
Example explained: The number 7 should be inserted on index 1 to remain the sort order.
The method starts the search from the left and returns the first index where the number 7 is no longer larger than the next value.
Search From the Right Side
By default the left most index is returned, but we can give side=’right’ to return the right most index instead.
Example
Find the indexes where the value 7 should be inserted, starting from the right:
x = np.searchsorted(arr, 7, side=’right’)
Example explained: The number 7 should be inserted on index 2 to remain the sort order.
The method starts the search from the right and returns the first index where the number 7 is no longer less than the next value.
Multiple Values
To search for more than one value, use an array with the specified values.
Example
Find the indexes where the values 2, 4, and 6 should be inserted:
x = np.searchsorted(arr, [2, 4, 6])
The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would be inserted in the original array to maintain the order.
Find element in array python numpy
Universal Functions
Working With Images
Projects and Applications with NumPy
Introduction
Creating NumPy Array
- Numpy | Array Creation
- numpy.arange() in Python
- numpy.zeros() in Python
- Create a Numpy array filled with all ones
- numpy.linspace() in Python
- numpy.eye() in Python
- Creating a one-dimensional NumPy array
- How to create an empty and a full NumPy array?
- Create a Numpy array filled with all zeros | Python
- How to generate 2-D Gaussian array using NumPy?
- How to create a vector in Python using NumPy
- Python | Numpy fromrecords() method
NumPy Array Manipulation
- Copy and View in NumPy Array
- How to Copy NumPy array into another array?
- Appending values at the end of an NumPy array
- How to swap columns of a given NumPy array?
- Insert a new axis within a NumPy array
- numpy.hstack() in Python
- numpy.vstack() in python
- Joining NumPy Array
- Combining a one and a two-dimensional NumPy Array
- Python | Numpy np.ma.concatenate() method
- Python | Numpy dstack() method
- Splitting Arrays in NumPy
- How to compare two NumPy arrays?
- Find the union of two NumPy arrays
- Find unique rows in a NumPy array
- Python | Numpy np.unique() method
- numpy.trim_zeros() in Python
Matrix in NumPy
- Matrix manipulation in Python
- numpy matrix operations | empty() function
- numpy matrix operations | zeros() function
- numpy matrix operations | ones() function
- numpy matrix operations | eye() function
- numpy matrix operations | identity() function
- Adding and Subtracting Matrices in Python
- Matrix Multiplication in NumPy
- Numpy ndarray.dot() function | Python
- NumPy | Vector Multiplication
- How to calculate dot product of two vectors in Python?
- Multiplication of two Matrices in Single line using Numpy in Python
- Python | Numpy np.eigvals() method
- How to Calculate the determinant of a matrix using NumPy?
- Python | Numpy matrix.transpose()
- Python | Numpy matrix.var()
- Compute the inverse of a matrix using NumPy
Operations on NumPy Array
Reshaping NumPy Array
- Reshape NumPy Array
- Python | Numpy matrix.resize()
- Python | Numpy matrix.reshape()
- NumPy Array Shape
- Change the dimension of a NumPy array
- numpy.ndarray.resize() function – Python
- Flatten a Matrix in Python using NumPy
- numpy.moveaxis() function | Python
- numpy.swapaxes() function | Python
- Python | Numpy matrix.swapaxes()
- numpy.vsplit() function | Python
- numpy.hsplit() function | Python
- Numpy MaskedArray.reshape() function | Python
- Python | Numpy matrix.squeeze()
Indexing NumPy Array
Arithmetic operations on NumPyArray
Linear Algebra in NumPy Array
NumPy and Random Data
- Random sampling in numpy | ranf() function
- Random sampling in numpy | random() function
- Random sampling in numpy | random_sample() function
- Random sampling in numpy | sample() function
- Random sampling in numpy | random_integers() function
- Random sampling in numpy | randint() function
- numpy.random.choice() in Python
- How to choose elements from the list with different probability using NumPy?
- How to get weighted random choice in Python?
- numpy.random.shuffle() in python
- numpy.random.geometric() in Python
- numpy.random.permutation() in Python
Universal Functions
Working With Images
Find the index of value in Numpy Array using numpy.where()
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, elements 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')
Frequently Asked:
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.
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.
[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.
If element not found in numpy array
# 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')
Empty Array returned : (array([], dtype=int32),) value 111 exists at following indices []
Find index of a value in 2D Numpy array | Matrix
# Create a 2D Numpy array from list of lists arr = np.array([[11, 12, 13], [14, 15, 16], [17, 15, 11], [12, 14, 15]])
[[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)
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.
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.
# 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.
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')
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])
First Index of element with value 15 is 4
Complete example is as follows,
import numpy as np 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])
*** 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
Summary
Today, we learned about different ways to find the indices of elements in a NumPy Array.