w3resource

NumPy: Check whether a Numpy array contains a specified row


Check if an array contains a specified row.

Write a NumPy program to check whether a Numpy array contains a specified row.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Generating a NumPy array of integers from 0 to 19 (exclusive) and reshaping it to a 4x5 matrix
num = np.arange(20)
arr1 = np.reshape(num, [4, 5])

# Displaying a message indicating the original array
print("Original array:")
print(arr1)

# Checking if [0, 1, 2, 3, 4] is present as a sublist in the array, converting the array to a list using tolist()
print([0, 1, 2, 3, 4] in arr1.tolist())

# Checking if [0, 1, 2, 3, 5] is present as a sublist in the array, converting the array to a list using tolist()
print([0, 1, 2, 3, 5] in arr1.tolist())

# Checking if [15, 16, 17, 18, 19] is present as a sublist in the array, converting the array to a list using tolist()
print([15, 16, 17, 18, 19] in arr1.tolist()) 

Sample Output:

Original array:
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
True
False
True

Explanation:

In the above code -

num = np.arange(20): This code creates a NumPy array with integers from 0 to 19.

arr1 = np.reshape(num, [4, 5]): This code reshapes the NumPy array 'num' into a 4x5 array (4 rows and 5 columns).

[0, 1, 2, 3, 4] in arr1.tolist(): Convert the NumPy array 'arr1' to a nested list using tolist() and check if the list [0, 1, 2, 3, 4] is present as a row in the list.

[0, 1, 2, 3, 5] in arr1.tolist(): Check if the list [0, 1, 2, 3, 5] is present as a row in the list converted from 'arr1'.

[15, 16, 17, 18, 19] in arr1.tolist(): Check if the list [15, 16, 17, 18, 19] is present as a row in the list converted from 'arr1'.

Note: ndarray.tolist()

Return the array as a (possibly nested) list. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible Python type.

Pictorial Presentation:

NumPy: Check whether a Numpy array contains a specified row

For more Practice: Solve these Related Problems:

  • Write a NumPy program to check if a given row exists in a 2D array using np.all and broadcasting.
  • Create a function that iterates over rows of a matrix and returns True if an exact match is found.
  • Implement a solution that converts both the target row and each row of the array to strings for comparison.
  • Test the function on arrays with duplicate rows and near-matches to ensure it only returns exact matches.

Go to:


PREV : Zero out elements below k-th diagonal.
NEXT : Calculate averages without NaN.


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.