wie man Indizes eines 2d numpy Arrays findet, die in einem anderen 2d Array vorkommen [Duplikat]

Nov 25 2020

Ich habe zwei 2d numpy Arrays und möchte herausfinden, wo ein Array in einem anderen vorkommt:

big_array = np.array([[1., 2., 1.2], [5., 3., 0.12], [-1., 14., 0.], [-9., 0., 13.]])
small_array= np.array([[5., 3., 0.12], [-9., 0., 13.]])

Dann möchte ich die Indizes der Zeilen erhalten, von big_arraydenen alle Zeilen von identisch sind small_array. Ich möchte so etwas wie np.in1dfür 2D-Arrays machen. Ich meine, ich möchte haben:

result= [1, 3]

Ich habe bereits den folgenden Code ausprobiert, aber er war nicht erfolgreich:

result=[([any(i == big_array ) for i in small_array])]

Im Voraus freue ich mich über jede Hilfe.

Antworten

1 Djib2011 Nov 25 2020 at 08:56

Was Sie wollen ist:

sum([row in small_array for row in big_array])

Beispiel:

import numpy as np
big_array = np.array([[1., 2., 1.2], [5., 3., 0.12], [-1., 14., 0.], [-9., 0., 13.]])
small_array= np.array([[5., 3., 0.12], [-1., 14., 0.]])

result = sum([row in small_array for row in big_array])
print(result)

2


Bearbeiten (nach Klarstellungen):

Eine pythonische Lösung:

[i for i, brow in enumerate(big_array) for srow in small_array if all(srow == brow)]

Beispiel:

big_array = np.array([[1., 2., 1.2], [5., 3., 0.12], [-1., 14., 0.], [-9., 0., 13.]])
small_array= np.array([[5., 3., 0.12], [-1., 14., 0.]])

result = [i for i, brow in enumerate(big_array) for srow in small_array if all(srow == brow)]

print(result)

[1, 2]

Hinweis : Sie könnten wahrscheinlich etwas Besseres tun np.where, wenn Sie große Arrays haben, sollten Sie es nachschlagen