Karnivaurus
Karnivaurus

Reputation: 24171

Testing whether a NumPy array contains a particular row

I want to create an n-by-2 NumPy array, and then test whether it contains a particular 1-by-2 array (i.e. whether it contains a particular row).

Here is my code:

x = np.array([0, 1])
y = np.array([2, 3])
z = np.vstack((x, y))
if x in z:
    print "Yes"

But this gives me the error:

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

Please could somebody explain this to me? Thanks!

Upvotes: 1

Views: 1469

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 78041

You may be using an older version of numpy since on 1.10 this does work;

>>> x = np.array([0, 1])
>>> y = np.array([2, 3])
>>> z = np.vstack((x, y))
>>> x in z
True
>>> np.__version__
'1.10.1'

That said, it does not do what you want:

>>> z
array([[0, 0],
       [0, 0]])
>>> x
array([0, 1])
>>> x in z
True

as commented out here, x in z is equivalent of (x == z).any(), not kind of row search that you want.


To implement what you need, you may do:

>>> (z == x).all(axis=1).any()
True

Upvotes: 1

Related Questions