What is the best way to convert a vector to a 2-dimensional array?
将矢量转换为二维数组的最佳方法是什么?
For example, a vector b of size (10, )
例如,大小为(10,)的向量b
a = rand(10,10)
b = a[1, :]
b.shape
Out: (10L,)
can be converted to array of size (10,1) as
可以转换为大小为(10,1)的数组
b = b.reshape(len(b), 1)
Is there a more concise way to do it?
有更简洁的方法吗?
2 个解决方案
#1
8
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:
由于在使用[1,:]进行索引时丢失了尺寸,因此需要更换丢失的尺寸以保持2D形状。考虑到这一点,您可以使用以下语法进行选择:
b = a[1, :, None]
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具有所需的形状(10,1)。请注意,None与np.newaxis相同,并插入长度为1的新轴。
(This is the same thing as writing b = a[1, :][:, None]
but uses only one indexing operation, hence saves a few microseconds.)
(这与写入b = a [1,:] [:,None]相同,但只使用一个索引操作,因此可以节省几微秒。)
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:
如果你想继续使用重塑(这也适用于此目的),值得记住你可以使用-1(最多)一个轴让NumPy找出正确长度应该是什么:
b.reshape(-1, 1)
#2
5
Use np.newaxis
:
In [139]: b.shape
Out[139]: (10,)
In [140]: b=b[:,np.newaxis]
In [142]: b.shape
Out[142]: (10, 1)
#1
8
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:
由于在使用[1,:]进行索引时丢失了尺寸,因此需要更换丢失的尺寸以保持2D形状。考虑到这一点,您可以使用以下语法进行选择:
b = a[1, :, None]
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具有所需的形状(10,1)。请注意,None与np.newaxis相同,并插入长度为1的新轴。
(This is the same thing as writing b = a[1, :][:, None]
but uses only one indexing operation, hence saves a few microseconds.)
(这与写入b = a [1,:] [:,None]相同,但只使用一个索引操作,因此可以节省几微秒。)
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:
如果你想继续使用重塑(这也适用于此目的),值得记住你可以使用-1(最多)一个轴让NumPy找出正确长度应该是什么:
b.reshape(-1, 1)
#2
5
Use np.newaxis
:
In [139]: b.shape
Out[139]: (10,)
In [140]: b=b[:,np.newaxis]
In [142]: b.shape
Out[142]: (10, 1)