簡體   English   中英

比較二維numpy arrays的元素

[英]Compare the elements of 2d numpy arrays

我有兩個 2d numpy arrays,a 和 b。 我想比較 b 數組中的每個元素是否都在數組 a 中。 例如,如果 [2,1] 在 [1,4,3,2] 中,則退出將為 True,如果 [2,1] 在 [3,1] 中,則退出將為 False 等等...相同的過程帶有 [1,3] 元素。 對於 [2,1] 元素,出口必須是 [True, False, False],對於 [1,3] 元素,出口必須是 [True, True, False]。

a = np.array([[1,4,3,2],[3,1],[1,7,8,9,4]])
b = np.array([[2,1],[1,3]])

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

一個簡單的方法是 -

In [80]: np.vstack([np.isin(b,i).all(1) for i in a])
Out[80]: 
array([[ True,  True],
       [False,  True],
       [False, False]])

看看 numpy.in1d function .. 它檢查第一個數組中的元素是否包含在第二個數組中:

In [18]: [[np.in1d(bx, ax).all() for ax in a] for bx in b]
Out[18]: [[True, False, False], [True, True, False]]

暫無
暫無

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

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