3

I need to find if a numpy array is inside other numpy array, but it seems to work different to python lists. I tried to search this question in numpy documentation and internet, but not answer. This is an example:

import numpy as np

m1=np.array([[1,2,3],[5,3,4]])
m2=np.array([5,4,3])
m2 in m1
True
m3=[[1,2,3],[5,3,4]]
m4=[5,4,3]
m4 in m3
False

In numpy I obtain True but with Python lists I obtain False. Is there any numpy function to make this work?

Thanks.

1
  • Is there a typo in m3? Did you mean m3 = [[1, 2, 3], [5, 4, 3]] in place of m3 = [[1, 2, 3], [5, 3, 4]]. Commented Nov 2, 2012 at 18:22

1 Answer 1

3

To get the same behavior as in for lists, you could do something like this:

any(np.all(row == m2) for row in m1)

That does the loop over rows in python, which isn't ideal, but it should work.

To understand what's going on with the numpy in, here's a description of the semantics of in from Robert Kern on the numpy mailing list:

It dates back to Numeric's semantics for bool(some_array), which would be True if any of the elements were nonzero. Just like any other iterable container in Python, x in y will essentially do

for row in y:
   if x == row:
       return True
return False

Iterate along the first axis of y and compare by boolean equality. In Numeric/numpy's case, this comparison is broadcasted. So that's why [3,6,4] works, because there is one row where 3 is in the first column. [4,2,345] doesn't work because the 4 and the 2 are not in those columns.

Probably, this should be considered a mistake during the transition to numpy's semantics of having bool(some_array) raise an exception. scalar in array should probably work as-is for an ND array, but there are several different possible semantics for array in array that should be explicitly spelled out, much like bool(some_array).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.