1

Defined a 1d array (or a 1d slice of a bigger array), like:

a=np.array([ 5, 12, 13])

if there some higher dimension array, like:

c1=np.array([[1, 2, 3], [ 5, 12, 13], [7, 8, 9]])
c2=np.array([[1, 2, 3], [ 5, 6, 7], [7, 8, 9]])

It turns out to be:

a in c1, a in c2
(True, True)

I would like that only the first condition, where a is consecutively contained as sub-array to be True. While a in c2 would give False. Is there any function taking care of that?

6
  • Isn't the first True not just accidentally true? If you change a to a=np.array([ 5, 12, 13]) the output is (True, False) and should be (False, False). Commented Jun 2, 2014 at 16:53
  • mmmh ... I just edit the formatting in case it was misleading (some extra space). However I don't get your point @andi. Commented Jun 2, 2014 at 16:58
  • Your code returns true when only one element of a is found in c1 or c2. But I think you want to check if the entire array is found in c1 or c2. Am I wrong? Commented Jun 2, 2014 at 17:04
  • 1
    Expected output for a in c1.T ? Commented Jun 2, 2014 at 17:17
  • Possible duplicate of testing whether a Numpy array contains a given row Commented Jun 3, 2014 at 7:54

2 Answers 2

2

You can use .tolist() and then call the functions normally:

>>> a=np.array([ 5, 12, 13])
>>> c1=np.array([[1, 2, 3], [ 5, 12, 13], [7, 8, 9]])
>>> c2=np.array([[1, 2, 3], [ 5, 6, 7], [7, 8, 9]])
>>> a.tolist() in c1.tolist(), a.tolist() in c2.tolist()
(True, False)
>>> 
Sign up to request clarification or add additional context in comments.

Comments

2

I think, this is what you want:

import numpy as np

a=np.array([ 5, 12, 13])

c1=np.array([[1, 2, 3], [5,12,13], [7, 8, 9]])
c2=np.array([[1, 2, 3], [5,6,7], [7, 8, 9]])

print any((a == x).all() for x in c1)
print any((a == x).all() for x in c2)

It outputs:

True
False

Edit: as moarningsun suggested, here a better version:

import numpy as np

a=np.array([ 5, 12, 13])

c1=np.array([[1, 2, 3], [5,12,13], [7, 8, 9]])
c2=np.array([[1, 2, 3], [5,6,7], [7, 8, 9]])

print np.any((a == c1).all(axis=1))
print np.any((a == c2).all(axis=1))

10 Comments

Although this will return true if the sub-array being searched for 'wraps' around to the next row.
Is this not what he wanted?
np.all takes an "axis" parameter, which is more efficient than the generator expression you have now
Sorry, I was not aware of this. Would you mind editing the answer? I would also be very interested.
It's just np.any((a == c1).all(axis=1)). It "broadcasts" a to the shape of c1.
|

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.