根据一维数组的索引和值构造二维numpy数组 [英] Construct two dimensional numpy array from indices and values of a one dimensional array

查看:98
本文介绍了根据一维数组的索引和值构造二维numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有

Y = np.array([2, 0, 1, 1])

由此,我想获得形状为(len(Y), 3)的矩阵X.在这种特殊情况下,X的第一行在第二个索引上应该有一个,而其他则为零. X的第二行应在0索引上有一个,否则应为零.明确地说:

From this I want to obtain a matrix X with shape (len(Y), 3). In this particular case, the first row of X should have a one on the second index and zero otherwhise. The second row of X should have a one on the 0 index and zero otherwise. To be explicit:

X = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 0]])

我如何产生这个矩阵? 我从

How do I produce this matrix? I started with

X = np.zeros((Y.shape[0], 3))

但随后无法从索引列表中找出如何填充/填充索引

but then couldn't figure out how to populate/fill in the ones from the list of indices

一如既往,感谢您的宝贵时间!

As always, thanks for your time!

推荐答案

也许:

>>> Y = np.array([2, 0, 1, 1])
>>> X = np.zeros((len(Y), 3))
>>> X[np.arange(len(Y)), Y] = 1
>>> X
array([[ 0.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.]])

这篇关于根据一维数组的索引和值构造二维numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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