¿Cómo uso una matriz booleana en 2-d para seleccionar de una matriz en 1-d por fila en numpy?

StackOverflow https://stackoverflow.com/questions/442218

  •  22-07-2019
  •  | 
  •  

Pregunta

Permítanme ilustrar esta pregunta con un ejemplo:

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 ahora contiene el resultado deseado, pero estoy seguro de que hay un método específico para hacer esto que evita la iteración explícita. ¿Qué es?

¿Fue útil?

Solución

Si entiendo su pregunta correctamente, simplemente puede usar la multiplicación de matrices:

result = numpy.dot(matrix, base)

Si el resultado debe tener la misma forma que en su ejemplo, simplemente agregue una nueva forma:

result = numpy.dot(matrix, base).reshape((5,1))

Si la matriz no es simétrica, tenga cuidado con el orden en puntos.

Otros consejos

Aquí hay otra forma fea de hacerlo:

n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))

Mi intento:

numpy.sum(matrix * base, axis=1)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top