python – 从一维数组的索引和值构造二维numpy数组

栏目: Python · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/18968660/construct-two-dimensional-numpy-array-from-indices-and-values-of-a-one-dimension

说我有

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

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

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

我该如何制作这个矩阵?

我开始了

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

但后来无法弄清楚如何填充/填写索引列表中的那些

一如既往,谢谢你的时间!

也许:
>>> 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.]])

翻译自:https://stackoverflow.com/questions/18968660/construct-two-dimensional-numpy-array-from-indices-and-values-of-a-one-dimension


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning iPhone and iPad Web Apps

Beginning iPhone and iPad Web Apps

Chris Apers、Daniel Paterson / Apress / 2010-12-15 / USD 39.99

It seems that everyone and her sister has developed an iPhone App—everyone except you, the hard-working web professional. And now with the introduction of the iPad, you may even feel farther behind. B......一起来看看 《Beginning iPhone and iPad Web Apps》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具