pythonarraysnumpy-ndarray

What is an equivalent of in operator for 2D Numpy array?


Using Python lists:

a = [[0, 1], [3, 4]]
b = [0, 2]
print(b in a)

I'm getting False as an output, but with Numpy arrays:

a = np.array([[0, 1], [3, 4]])
b = np.array([0, 2])
print(b in a)

I'm getting True as an output. What is an equivalent of in operator above for 2D Numpy arrays?


Solution

  • In the NumPy array case, b in a is interpreted as checking if any element of b is in a, rather than checking for the presence of b as a whole array.

    You can use the numpy.all function along with numpy.any to compare rows:

    a = np.array([[0, 1], [3, 4]])
    b = np.array([0, 2])
    
    is_row_present = np.any(np.all(a == b, axis=1))
    print(is_row_present)
    >>> False