1

让我用一个例子来说明这个问题:

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 的方法可以避免显式迭代。它是什么?

4

3 回答 3

1

如果我正确理解您的问题,您可以简单地使用矩阵乘法:

result = numpy.dot(matrix, base)

如果结果必须与您的示例具有相同的形状,只需添加一个重塑:

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

如果矩阵不对称,请注意点中的顺序。

于 2009-01-14T11:42:09.357 回答
0

这是另一种丑陋的做法:

n.apply_along_axis(base.__getitem__, 0, matrix).reshape((5,1))
于 2009-01-14T07:54:52.840 回答
0

我的尝试:

numpy.sum(matrix * base, axis=1)
于 2009-01-15T00:05:41.260 回答