Come posso usare un array booleano 2-d per selezionare da un array 1-d su una riga per riga in numpy?
Domanda
Permettetemi di illustrare questa domanda con un esempio:
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 ])
risultato
ora contiene il risultato desiderato, ma sono sicuro che esiste un metodo specifico per fare ciò che evita l'iterazione esplicita. Che cos'è?
Soluzione
Se capisco correttamente la tua domanda puoi semplicemente usare la moltiplicazione di matrici:
result = numpy.dot(matrix, base)
Se il risultato deve avere la stessa forma del tuo esempio, aggiungi semplicemente una risagoma:
result = numpy.dot(matrix, base).reshape((5,1))
Se la matrice non è simmetrica, fai attenzione all'ordine in punto.
Altri suggerimenti
Ecco un altro brutto modo di farlo:
n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))
Il mio tentativo:
numpy.sum(matrix * base, axis=1)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow