Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert row vector to column vector in NumPy

Tags:

import numpy as np  matrix1 = np.array([[1,2,3],[4,5,6]]) vector1 = matrix1[:,0] # This should have shape (2,1) but actually has (2,) matrix2 = np.array([[2,3],[5,6]]) np.hstack((vector1, matrix2))  ValueError: all the input arrays must have same number of dimensions 

The problem is that when I select the first column of matrix1 and put it in vector1, it gets converted to a row vector, so when I try to concatenate with matrix2, I get a dimension error. I could do this.

np.hstack((vector1.reshape(matrix2.shape[0],1), matrix2)) 

But this looks too ugly for me to do every time I have to concatenate a matrix and a vector. Is there a simpler way to do this?

like image 849
siamii Avatar asked Jul 12 '13 19:07

siamii


1 Answers

The easier way is

vector1 = matrix1[:,0:1] 

For the reason, let me refer you to another answer of mine:

When you write something like a[4], that's accessing the fifth element of the array, not giving you a view of some section of the original array. So for instance, if a is an array of numbers, then a[4] will be just a number. If a is a two-dimensional array, i.e. effectively an array of arrays, then a[4] would be a one-dimensional array. Basically, the operation of accessing an array element returns something with a dimensionality of one less than the original array.

like image 159
David Z Avatar answered Nov 02 '22 02:11

David Z