Fill a matrix from a matrix of indices

匆匆过客 提交于 2019-12-30 09:46:47

问题


I want to fill a matrix from an array of indices :

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.

The result is :

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.]])

As desired.

Question

Is there a way to do this in pure python/numpy without looping ?


回答1:


Use advanced-indexing after intialization -

x[np.arange(len(indx))[:,None], indx] = 1


来源:https://stackoverflow.com/questions/45108775/fill-a-matrix-from-a-matrix-of-indices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!