Friday, December 27, 2024
Google search engine
HomeLanguagesCheck whether a Numpy array contains a specified row

Check whether a Numpy array contains a specified row

In this article we will learn about checking a specified row is in NumPy array or not. If the given list is present in a NumPy array as a row then the output is True else False. The list is present in a NumPy array means any row of that numpy array matches with the given list with all elements in given order. This can be done by using simple approach as checking for each row with the given list but this can be easily understood and implemented by using inbuilt library functions numpy.array.tolist().

Syntax: ndarray.tolist()

Parameters: none

Returns: The possibly nested list of array elements.

Examples :

Arr = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]

and the given lists are as follows :

lst  = [1,2,3,4,5]              True, as it matches with the row 0.
      [16,17,20,19,18]         False, as it doesn’t match with any row.
      [3,2,5,-4,5]             False, as it doesn’t match with any row.
      [11,12,13,14,15]         True, as it matches with the row 2.

Below is the implementation with an example :

Python3




# importing package
import numpy
  
# create numpy array
arr = numpy.array([[1, 2, 3, 4, 5],
                   [6, 7, 8, 9, 10],
                   [11, 12, 13, 14, 15],
                   [16, 17, 18, 19, 20]
                   ])
  
# view array
print(arr)
  
# check for some lists
print([1, 2, 3, 4, 5] in arr.tolist())
print([16, 17, 20, 19, 18] in arr.tolist())
print([3, 2, 5, -4, 5] in arr.tolist())
print([11, 12, 13, 14, 15] in arr.tolist())


Output :

[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
True
False
False
True
RELATED ARTICLES

Most Popular

Recent Comments