Python: Differentiating between row and column vectors
You can make the distinction explicit by adding another dimension to the array.
>>> a = np.array([1, 2, 3])>>> aarray([1, 2, 3])>>> a.transpose()array([1, 2, 3])>>> a.dot(a.transpose())14
Now force it to be a column vector:
>>> a.shape = (3,1)>>> aarray([[1], [2], [3]])>>> a.transpose()array([[1, 2, 3]])>>> a.dot(a.transpose())array([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
Another option is to use np.newaxis when you want to make the distinction:
>>> a = np.array([1, 2, 3])>>> aarray([1, 2, 3])>>> a[:, np.newaxis]array([[1], [2], [3]])>>> a[np.newaxis, :]array([[1, 2, 3]])
The vector you are creating is neither row nor column. It actually has 1 dimension only. You can verify that by
- checking the number of dimensions
myvector.ndim
which is1
- checking the
myvector.shape
, which is(3,)
(a tuple with one element only). For a row vector is should be(1, 3)
, and for a column(3, 1)
Two ways to handle this
- create an actual row or column vector
reshape
your current one
You can explicitly create a row or column
row = np.array([ # one row with 3 elements [1, 2, 3]]column = np.array([ # 3 rows, with 1 element each [1], [2], [3]])
or, with a shortcut
row = np.r_['r', [1,2,3]] # shape: (1, 3)column = np.r_['c', [1,2,3]] # shape: (3,1)
Alternatively, you can reshape it to (1, n)
for row, or (n, 1)
for column
row = my_vector.reshape(1, -1)column = my_vector.reshape(-1, 1)
where the -1
automatically finds the value of n
.