What is the best way to convert a vector to a 2-dimensional array?
For example, a vector b of size (10, )
a = rand(10,10) b = a[1, :] b.shape Out: (10L,) can be converted to array of size (10,1) as
b = b.reshape(len(b), 1) Is there a more concise way to do it?
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] 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.
(This is the same thing as writing b = a[1, :][:, None] but uses only one indexing operation, hence saves a few microseconds.)
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)
Use np.newaxis:
In [139]: b.shape Out[139]: (10,) In [140]: b=b[:,np.newaxis] In [142]: b.shape Out[142]: (10, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With