将NumPy向量转换为2D数组/矩阵 [英] Convert NumPy vector to 2D array / matrix

查看:1185
本文介绍了将NumPy向量转换为2D数组/矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将向量转换为二维数组的最佳方法是什么?

What is the best way to convert a vector to a 2-dimensional array?

例如,向量b的大小为(10,)

For example, a vector b of size (10, )

a = rand(10,10)
b = a[1, :]
b.shape

Out: (10L,)

可以转换为大小为(10,1)的数组,

can be converted to array of size (10,1) as

b = b.reshape(len(b), 1)

是否有更简洁的方法?

推荐答案

由于使用a[1, :]编制索引时丢失了尺寸,因此需要替换丢失的尺寸以保持2D形状.考虑到这一点,您可以使用以下语法进行选择:

Since you lose a dimension when indexing with a[1, :], the lost dimension needs to be replaced to maintain a 2D shape. With this in mind, you can make the selection using the syntax:

b = a[1, :, None]

然后b具有所需的形状(10,1).请注意,Nonenp.newaxis相同,并插入了一个长度为1的新轴.

Then b has the required shape of (10, 1). Note that None is the same as np.newaxis and inserts a new axis of length 1.

(这与编写b = a[1, :][:, None]相同,但是仅使用一个索引操作,因此节省了几微秒的时间.)

(This is the same thing as writing b = a[1, :][:, None] but uses only one indexing operation, hence saves a few microseconds.)

如果您想继续使用reshape(对于此目的也很好),值得记住的是,您最多可以对一个轴使用-1,以使NumPy找出应该正确的长度,而不是:

If you want to continue using reshape (which is also fine for this purpose), it's worth remembering that you can use -1 for (at most) one axis to have NumPy figure out what the correct length should be instead:

b.reshape(-1, 1)

这篇关于将NumPy向量转换为2D数组/矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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