Check whether a Numpy array contains a specified row

Learn, how to check whether a Numpy array contains a specified row in Python?
Submitted by Pranit Sharma, on January 21, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a NumPy array and we need to check whether a Numpy array contains at least one instance of a given row. It must terminate upon finding the first matching row rather than iterating over the entire array even if a result has already been found.

Checking whether a Numpy array contains a specified row

For this purpose, we will use the tolist() method with our NumPy array and check whether the given row is present in the array or not.

Let us understand with the help of an example,

Python code to check whether a Numpy array contains a specified row

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[1,2],[10,20],[100,200]])

# Display original array
print("Original Array:\n",arr,"\n")

# Check that a rows is present in this array or not
res = [1,2] in arr.tolist()

# Display result
print("Is [1,2] present in array:\n",res,"\n")

# Check for another row
res = [10,2] in arr.tolist()

# Display result
print("Is [10,2] present in array:\n",res,"\n")

Output

Example: Check whether a Numpy array contains a specified row

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.