0
a = np.array([1,2,4,2,3,4,1])
s = [1,2]

How can I get an array which tells me whether the elements in s exist in a? This is what I'm hoping to get:

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

3 Answers 3

5

Use np.isin

>>> np.isin(a,s)

array([ True,  True, False,  True, False, False,  True])
Sign up to request clarification or add additional context in comments.

Comments

0

no numpy, you can do like this

a = [1,2,4,2,3,4,1]
s = [1,2]
t = list(map(lambda a: a in s, a))

if is s is larger, set is more effective

 a = [1,2,4,2,3,4,1]
 s = set([1,2])
 t = list(map(lambda a: a in s, a))

1 Comment

This is way slower than np.isin
0
import numpy as np

a = np.array([1, 2, 4, 2, 3, 4, 1])
s = [1, 2]
r = [n in s for n in a]
print(r)  # [True, True, False, True, False, False, True]

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.