Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NumPy vector to 2D array / matrix

Tags:

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?

like image 862
Alexandr M. Avatar asked Nov 02 '15 15:11

Alexandr M.


2 Answers

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) 
like image 113
Alex Riley Avatar answered Mar 03 '23 08:03

Alex Riley


Use np.newaxis:

In [139]: b.shape Out[139]: (10,)  In [140]: b=b[:,np.newaxis]  In [142]: b.shape Out[142]: (10, 1) 
like image 36