测试数组的每个元素是否在另一个数组中

时间:2018-03-06 16:09:47

标签: python python-3.x pandas numpy

假设我有两个数组xy,其中yx的子集:

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

我想返回一个像:

这样的数组
ret = [False, False, True, True, False, False, True, False, False]

如果y只是一个数字,那就很容易(x == y),但我尝试了等效的x in y,但它没有用。当然,我可以通过for循环来实现,但我更倾向于采用更简洁的方式。

我已经标记了此Pandas,因为x实际上是Pandas系列(数据框中的一列)。 y是一个列表,但如果需要,可以将其设置为NumPy数组或系列。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

IIUC:

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

输出:

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

并返回列表:

s.isin(y).tolist()

输出:

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

答案 2 :(得分:0)

Set Intersection也可以为你做这件事。

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)
相关问题