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


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

查看所有标签

猜你喜欢:

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

A Common-Sense Guide to Data Structures and Algorithms

A Common-Sense Guide to Data Structures and Algorithms

Jay Wengrow / Pragmatic Bookshelf / 2017-8-13 / USD 45.95

If you last saw algorithms in a university course or at a job interview, you’re missing out on what they can do for your code. Learn different sorting and searching techniques, and when to use each. F......一起来看看 《A Common-Sense Guide to Data Structures and Algorithms》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具