comment trouver les indices d'un tableau numpy 2d apparaissant dans un autre tableau 2d [dupliquer]

Nov 25 2020

J'ai deux tableaux numpy 2d et je veux trouver où un tableau se produit dans un autre:

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.]])

Ensuite, je veux obtenir les indices des lignes big_arraydont sont les mêmes que toutes les lignes de small_array. Je veux faire quelque chose comme np.in1dpour les tableaux 2D. Je veux dire que je veux avoir:

result= [1, 3]

J'ai déjà essayé le code suivant mais cela n'a pas réussi:

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

À l'avance, j'apprécie toute aide.

Réponses

1 Djib2011 Nov 25 2020 at 08:56

Ce que tu veux c'est:

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

Exemple:

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


Edit (après clarifications):

Une solution pythonique:

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

Exemple:

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]

Remarque : vous pourriez probablement faire quelque chose de mieux avec np.where, si vous avez d'énormes tableaux, vous devriez le rechercher