0

Suppose I have two arrays, x and y, where y is a subset of x:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [3, 4, 7]

I want to return an array like:

ret = [False, False, True, True, False, False, True, False, False]

If y were just a single number it would be easy enough (x == y), but I tried the equivalent x in y and it didn't work. Of course, I could do it with a for loop, but I'd rather there was a neater way.

I've tagged this Pandas since x is actually a Pandas series (a column in a dataframe). y is a list, but can be made to be a NumPy array or Series if needed.

gautampk
  • 109
  • 1
  • 1
  • 2

3 Answers3

3
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [3, 4, 7]
print([x in y for x in x])
fourmajor
  • 51
  • 5
3

IIUC:

s = pd.Series(x)
s.isin(y)

Output:

0    False
1    False
2     True
3     True
4    False
5    False
6     True
7    False
8    False
dtype: bool

And to return list:

s.isin(y).tolist()

Output:

[False, False, True, True, False, False, True, False, False]
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

Set Intersection can also do this for you.

a = [1,2,3,4,5,9,11,15]
b = [4,5,6,7,8]
c = [True if x in list(set(a).intersection(b)) else False for x in a]

print(c)
eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20