7

I'd like to return a boolean for each value in array A that indicates whether it's in array B. This should be a standard procedure I guess, but I can't find any information on how to do it. My attempt is below:

A = ['User0','User1','User2','User3','User4','User0','User1','User2','User3'
     'User4','User0','User1','User2','User3','User4','User0','User1','User2'
     'User3','User4','User0','User1','User2','User3','User4','User0','User1'
     'User2','User3','User4','User0','User1']
B = ['User3', 'User2', 'User4']
contained = (A in B)

However, I get the error:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

I'm using numpy so any solution using numpy or standard Python would be preferred.

0

2 Answers 2

21

You can use in1d I believe -

np.in1d(A,B)
Sign up to request clarification or add additional context in comments.

Comments

6

For testing it without using numpy, try:

contained = [a in B for a in A]

result:

[False, False, True, True, True, False, False, True, False, False,
 False, True, True, True, False, False, False, True, False, False,
 True, True, True, False, False, True, True, False, False]

1 Comment

For this small example, this list comprehension is considerably faster than np.in1d.

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.