w3resource

NumPy: Search the index of a given array in another given array


Search for a sub-array in a larger array.

Write a NumPy program to search the index of a given array in another given array.

Sample Solution:

Python Code:

# Importing NumPy library
import numpy as np

# Creating a NumPy array
np_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

# Creating another NumPy array for searching
test_array = np.array([4, 5, 6])

# Printing the original NumPy array and the array to be searched
print("Original NumPy array:")
print(np_array)
print("Searched array:")
print(test_array)

# Finding the index of the searched array in the original array
# Using np.where() to locate rows where all elements match the test_array
result = np.where((np_array == test_array).all(1))[0]

# Printing the index of the searched array in the original array
print("Index of the searched array in the original array:")
print(result) 

Sample Output:

Original Numpy array:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
Searched array:
[4 5 6]
Index of the searched array in the original array:
[1]

Explanation:

np_array = np.array([[1,2,3], [4,5,6] , [7,8,9], [10, 11, 12]]): This line creates a 4x3 NumPy array.

test_array = np.array([4,5,6]): This line creates a 1D NumPy array.

np.where((np_array == test_array).all(1))[0]

  • (np_array == test_array) compares each element in np_array with the corresponding element in test_array, creating a boolean array with the same shape as np_array.
  • .all(1) checks if all elements along axis 1 (columns) are True. It returns a 1D boolean array with the length equal to the number of rows in np_array. If a row in the resulting array is True, it means that the entire row in np_array matches test_array.
  • np.where( ... )[0] finds the index of the True values in the 1D boolean array.

Pictorial Presentation:

NumPy: Search the index of a given array in another given array

For more Practice: Solve these Related Problems:

  • Write a NumPy program to locate the starting index of a 1D sub-array within a larger 1D array using sliding window comparison.
  • Create a function that searches for a 2D sub-array within a larger 2D array and returns its top-left index.
  • Implement a solution that uses np.where to identify positions where the sub-array may match and then verifies the full pattern.
  • Test the sub-array search on arrays with multiple occurrences and overlapping candidates for robustness.

Go to:


PREV : Count occurrences of sequences in a 2D array.
NEXT : Store non-zero unique rows from a matrix.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.