w3resource

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

NumPy: Array Object Exercise-171 with Solution

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

Python-Numpy Code Editor:

Previous: Write a NumPy program to get all 2D diagonals of a 3D NumPy array.
Next: Write a Numpy program to find and store non-zero unique rows in an array after comparing each row with other row in a given matrix.

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.