Comment utiliser un tableau booléen 2-D pour sélectionner un tableau 1-d sur une base ligne par ligne dans numpy?
Question
Permettez-moi d'illustrer cette question par un exemple:
import numpy
matrix = numpy.identity(5, dtype=bool) #Using identity as a convenient way to create an array with the invariant that there will only be one True value per row, the solution should apply to any array with this invariant
base = numpy.arange(5,30,5) #This could be any 1-d array, provided its length is the same as the length of axis=1 of matrix from above
result = numpy.array([ base[line] for line in matrix ])
result
contient maintenant le résultat souhaité, mais je suis sûr qu'il existe une méthode spécifique à Numpy qui évite l'itération explicite. Qu'est-ce que c'est?
La solution
Si je comprends bien votre question, vous pouvez simplement utiliser la multiplication matricielle:
result = numpy.dot(matrix, base)
Si le résultat doit avoir la même forme que dans votre exemple, ajoutez simplement un remodelage:
result = numpy.dot(matrix, base).reshape((5,1))
Si la matrice n'est pas symétrique, faites attention à l'ordre dans le point.
Autres conseils
Voici une autre façon laide de le faire:
n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))
Mon essai:
numpy.sum(matrix * base, axis=1)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow