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

私の試み:

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

これを行う別の醜い方法を次に示します。

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