如何使用一个2-d布尔数组从1-d阵列选择在每行的基础上在numpy的?
题
让我示出了与一个示例这样的问题:
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
现在拥有了想要的结果,但我敢肯定有这样做避免了显式迭代特定numpy的法。这是什么?
解决方案
如果我正确地理解你的问题,你可以简单地使用矩阵乘法:
result = numpy.dot(matrix, base)
如果结果必须具有相同的形状在实施例只是添加重塑:
result = numpy.dot(matrix, base).reshape((5,1))
如果矩阵不是对称小心以点顺序。
其他提示
下面是这样做的另一个丑陋的方式:
n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))
我尝试:
numpy.sum(matrix * base, axis=1)
不隶属于 StackOverflow