簡體   English   中英

如何在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獲取匹配的數字,它將返回匹配的值,並且無需循環即可完成:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM