numpyで2次元ブール配列を使用して行ごとに1次元配列から選択するにはどうすればよいですか?

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

  •  22-07-2019
  •  | 
  •  

質問

例を使ってこの質問を説明させてください:

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top