Home > database >  Numpy python Check if row equals 2d array
Numpy python Check if row equals 2d array

Time:03-18

import numpy as np

a = np.array([
    [1,2,3],
    [4,5,6],
    [7,8,9]
])

if a[0] == [1, 2, 3]:
    print("equal")

this is the code i've tried but gives following error:

Exception has occurred: ValueError The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

CodePudding user response:

Just use np.all(), as the error message tells you. Doing == on a numpy array will return an that's the same shape as the original array, only with True and False values in. They'll be True if the items at the particular index are equal, and False otherwise. .all() will only return True if every item in the array is True, so it will return True if the arrays are perfectly equal:

if np.all(a[0] == [1, 2, 3]):
    print("equal")

Output:

equal

CodePudding user response:

You could simply use numpy.array_equal:

In [32]: if np.array_equal(a[0], [1, 2, 3]):
    ...:     print("equal")
equal
  • Related