Convert NumPy vector to 2D array / matrix

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)