How do I use a 2-d boolean array to select from a 1-d array on a per-row basis in numpy?
Question
Let me illustrate this question with an example:
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
now holds the desired result, but I'm sure there is a numpy-specific method for doing this that avoids the explicit iteration. What is it?
Solution
If I understand your question correctly you can simply use matrix multiplication:
result = numpy.dot(matrix, base)
If the result must have the same shape as in your example just add a reshape:
result = numpy.dot(matrix, base).reshape((5,1))
If the matrix is not symmetric be careful about the order in dot.
OTHER TIPS
Here is another ugly way of doing it:
n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))
My try:
numpy.sum(matrix * base, axis=1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow