从索引矩阵填充矩阵

Too*_*ool 5 python numpy matrix

我想从索引数组填充矩阵:

import numpy as np

indx = [[0,1,2],[1,2,4],[0,1,3],[2,3,4],[0,3,4]]
x = np.zeros((5,5))
for i in range(5):
    x[i,indx[i]] = 1.
Run Code Online (Sandbox Code Playgroud)

结果是:

array([[ 1.,  1.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  0.,  1.],
       [ 1.,  1.,  0.,  1.,  0.],
       [ 0.,  0.,  1.,  1.,  1.],
       [ 1.,  0.,  0.,  1.,  1.]])
Run Code Online (Sandbox Code Playgroud)

如预期的.

有没有办法在没有循环的纯python/numpy中执行此操作?

Div*_*kar 5

advanced-indexing初始化后使用-

x[np.arange(len(indx))[:,None], indx] = 1
Run Code Online (Sandbox Code Playgroud)