从索引矩阵填充矩阵 [英] Fill a matrix from a matrix of indices

查看:88
本文介绍了从索引矩阵填充矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

结果是:

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

根据需要.

有没有一种方法可以在纯python/numpy中做到这一点而无需循环?

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

推荐答案

使用

Use advanced-indexing after intialization -

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

这篇关于从索引矩阵填充矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆