如何屏蔽 Python 中第二个数组中不存在的数组元素?
How do I mask an arrays elements that aren't present in a second array in Python?
这是我目前拥有的:
x = range(10)
x2 = array(x)
y = [3,6,8]
for i in range(len(x)):
x2[i] = x2[i] in y
x = ma.masked_where(x2 == False, x)
这让我得到了我想要的东西,但我想在不循环的情况下这样做。
有什么方法可以屏蔽 y 中不存在值的数组 x?
这种使用列表理解的方法不依赖于任何 numpy 结构。如果它在 y
中,它会保留数字,如果它不在
中,它会放入一个 -
x = [i if i in y else '-' for i in range(10)]
输出
['-', '-', '-', 3, '-', '-', 6, '-', 8, '-']
如果您想更改掩码的默认值,请更改“-”。
您可以使用 set.intersection 来获取匹配的数字,它将 return 您匹配的值,并且无需循环即可完成:
x = range(10)
y = [3,6,8]
s1 = set(x)
s2 = set(y)
s1.intersection(s2)
(Output:) set([8, 3, 6])
x = [1,2,3,4,5]
y = [2,3,6,7,8]
s1 = set(x)
s2 = set(y)
s1.intersection(s2)
(Output:) set([2, 3])
您可以通过投集获得列表:
y = list(s1.intersection(s2))
您可以使用 numpy
为您执行循环,从而加速计算。
x = np.arange(10)
y = np.array([3,6,8])
mask = np.all( x!=y[:,None], 0 )
x = np.ma.masked_where(mask,x)
这是我目前拥有的:
x = range(10)
x2 = array(x)
y = [3,6,8]
for i in range(len(x)):
x2[i] = x2[i] in y
x = ma.masked_where(x2 == False, x)
这让我得到了我想要的东西,但我想在不循环的情况下这样做。 有什么方法可以屏蔽 y 中不存在值的数组 x?
这种使用列表理解的方法不依赖于任何 numpy 结构。如果它在 y
中,它会保留数字,如果它不在
-
x = [i if i in y else '-' for i in range(10)]
输出
['-', '-', '-', 3, '-', '-', 6, '-', 8, '-']
如果您想更改掩码的默认值,请更改“-”。
您可以使用 set.intersection 来获取匹配的数字,它将 return 您匹配的值,并且无需循环即可完成:
x = range(10)
y = [3,6,8]
s1 = set(x)
s2 = set(y)
s1.intersection(s2)
(Output:) set([8, 3, 6])
x = [1,2,3,4,5]
y = [2,3,6,7,8]
s1 = set(x)
s2 = set(y)
s1.intersection(s2)
(Output:) set([2, 3])
您可以通过投集获得列表:
y = list(s1.intersection(s2))
您可以使用 numpy
为您执行循环,从而加速计算。
x = np.arange(10)
y = np.array([3,6,8])
mask = np.all( x!=y[:,None], 0 )
x = np.ma.masked_where(mask,x)