簡體   English   中英

Numpy 在兩個 arrays 中找到相同的元素

[英]Numpy find identical element in two arrays

假設我有一個數組ab ,如何在兩個 arrays 中找到相同的元素?

a = np.array([[262.5, 262.5, 45],
              [262.5, 262.5, 15],
              [262.5, 187.5, 45],
              [262.5, 187.5, 15],
              [187.5, 262.5, 45],
              [187.5, 262.5, 15],
              [187.5, 187.5, 45],
              [187.5, 187.5, 15]])

b = np.array([[262.5, 262.5, 45],
              [262.5, 262.5, 15],
              [3,3,5],
              [5,5,7],
              [8,8,9]])

我嘗試了下面的代碼,但 output 不是我想要的,誰能告訴我這段代碼有什么問題? 或者還有其他方法嗎?

out = [x[(x == b[:,None]).all(1).any(0)] for x in a]

我要的output是:

array[[262.5, 262.5, 45],
      [262.5, 262.5, 15]]

如果您沒有一直使用np (我認為是這種情況,請參閱列表理解) - 您可以進行set交集

x = set(map(tuple, a)).intersection(set(map(tuple, b)))
print(x)
# {(262.5, 262.5, 15.0), (262.5, 262.5, 45.0)}

您可以通過以下方式將其轉換回np.ndarray

xarr = np.array(list(x)) 
print(xarr)
# array([[262.5, 262.5,  45. ],
#       [262.5, 262.5,  15. ]])
a[np.all([np.isin(ai, b) for ai in  a], axis=1)]

或者還有:

b[np.all([np.isin(bi, a) for bi in  b], axis=1)]

目前尚不清楚您是否想要第一個連續的塊。 假設不是,並且您想要檢索 arrays 中相同索引的所有行,並且所有元素都相等:

import numpy as np

a = np.array(
    [
        [1, 1, 1],
        [2, 2, 2],
        [3, 3, 3],
        [4, 4, 4],
        [5, 5, 5],
        [6, 6, 6],
    ]
)

b = np.array(
    [
        [1, 1, 1],
        [2, 2, 2],
        [0, 0, 0],
        [0, 0, 0],
        [5, 5, 5],
    ]
)

expected = np.array(
    [
        [1, 1, 1],
        [2, 2, 2],
        [5, 5, 5],
    ]
)

第一種方法是使用 for 循環,但可能效率不高:

out = np.array([x for x, y in zip(a, b) if np.all(x == y)])
assert np.all(out == expected)

第二種方法是矢量化的並且效率更高,您只需要事先裁剪 arrays 因為它們的長度不同( zip會默默地這樣做):

num_rows = min(a.shape[0], b.shape[0])
a_ = a[:num_rows]
b_ = b[:num_rows]

rows_mask = np.all(a_ == b_, axis=-1)
out = a_[rows_mask, :]

assert np.all(out == expected)

暫無
暫無

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

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