ฉันจะค้นหาแถวที่เหมือนกันในอาร์เรย์ต่างๆโดยไม่คำนึงถึงลำดับองค์ประกอบโดยใช้ Numpy ได้อย่างไร [ซ้ำ]

Aug 19 2020

ฉันกำลังทำโครงการและพบปัญหานี้ ฉันมีอาร์เรย์สองอาร์เรย์ A และ B ของรูปร่าง (8,3) และ (2,2) ฉันจะค้นหาแถวทั้งหมดของ A ที่มีองค์ประกอบของแต่ละแถวของ B โดยไม่คำนึงถึงลำดับขององค์ประกอบใน B ได้อย่างไร

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

ขอบคุณ!

คำตอบ

2 Geom Aug 19 2020 at 06:05

นี่เป็นวิธีหนึ่งที่ทำได้:

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]