Numpyを使用して、要素の順序に関係なく、異なる配列で同一の行を見つけるにはどうすればよいですか?[複製]

Aug 19 2020

私はプロジェクトに取り組んでいて、この問題に遭遇しました。形状(8,3)と(2,2)の2つの配列AとBがあります。Bの要素の順序に関係なく、Bの各行の要素を含むAのすべての行を見つけるにはどうすればよいですか?

A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))

ありがとう!

回答

2 Geom Aug 19 2020 at 06:05

これを行う1つの方法は次のとおりです。

Import numpy as np

A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))

C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any((3,1)).all(1))[0]
print(rows)

出力:

[0 2 3 4]
2 BrycePaule Aug 19 2020 at 06:14
import numpy as np

A = np.random.randint(0, 5, (8, 3))
B = np.random.randint(0, 5, (2, 2))

for BRow in B:
    for ARow in A:
        if all(item in ARow for item in BRow):
            print(f'{BRow} in {ARow}')

ただし、これは重複をチェックしません。たとえば、 [3, 3] in [1, 2, 3]