Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with N by 1 matrices in Numpy

Given a numpy array of size (n,) how do you transform it to a numpy array of size (n,1).

The reason is because I am trying to matrix multiply to numpy arrays of size (n,) and (,n) to get a (n,n) but when I do:

numpy.dot(a,b.T)

It says that you can't do it. I know as a fact that transposing a (n,) does nothing, so it would just be nice to change the (n,) and make them (n,1) and avoid this problem all together.

like image 934
Charlie Parker Avatar asked Mar 21 '23 06:03

Charlie Parker


2 Answers

Use reshape (-1,1) to reshape (n,) to (n,1), see detail examples:

In [1]:

import numpy as np
A=np.random.random(10)
In [2]:

A.shape
Out[2]:
(10,)
In [3]:

A1=A.reshape(-1,1)
In [4]:

A1.shape
Out[4]:
(10, 1)
In [5]:

A.T
Out[5]:
array([ 0.6014423 ,  0.51400033,  0.95006413,  0.54321892,  0.2150995 ,
        0.09486603,  0.54560678,  0.58036358,  0.99914564,  0.09245124])
In [6]:

A1.T
Out[6]:
array([[ 0.6014423 ,  0.51400033,  0.95006413,  0.54321892,  0.2150995 ,
         0.09486603,  0.54560678,  0.58036358,  0.99914564,  0.09245124]])
like image 185
CT Zhu Avatar answered Mar 27 '23 18:03

CT Zhu


You can use None for dimensions that you want to be treated as degenerate.

a = np.asarray([1,2,3])
a[:]
a[:, None]

In [48]: a
Out[48]: array([1, 2, 3])

In [49]: a[:]
Out[49]: array([1, 2, 3])

In [50]: a[:, None]
Out[50]: 
array([[1],
       [2],
       [3]])
like image 39
ely Avatar answered Mar 27 '23 19:03

ely