Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating column vectors using numpy arrays

Tags:

I'd like to concatenate 'column' vectors using numpy arrays but because numpy sees all arrays as row vectors by default, np.hstack and np.concatenate along any axis don't help (and neither did np.transpose as expected).

a = np.array((0, 1)) b = np.array((2, 1)) c = np.array((-1, -1))  np.hstack((a, b, c)) # array([ 0,  1,  2,  1, -1, -1])  ## Noooooo np.reshape(np.hstack((a, b, c)), (2, 3)) # array([[ 0,  1,  2], [ 1, -1, -1]]) ## Reshaping won't help 

One possibility (but too cumbersome) is

np.hstack((a[:, np.newaxis], b[:, np.newaxis], c[:, np.newaxis])) # array([[ 0,  2, -1], [ 1,  1, -1]]) ## 

Are there better ways?

like image 909
green diod Avatar asked Feb 06 '13 23:02

green diod


People also ask

How do I combine two columns in NumPy?

NumPy's concatenate function can be used to concatenate two arrays either row-wise or column-wise. Concatenate function can take two or more arrays of the same shape and by default it concatenates row-wise i.e. axis=0. The resulting array after row-wise concatenation is of the shape 6 x 3, i.e. 6 rows and 3 columns.

Can you concatenate NumPy arrays?

Joining Arrays Using Stack FunctionsWe can concatenate two 1-D arrays along the second axis which would result in putting them one over the other, ie. stacking. We pass a sequence of arrays that we want to join to the stack() method along with the axis.

How do you stack columns in NumPy array?

column_stack() in Python. numpy. column_stack() function is used to stack 1-D arrays as columns into a 2-D array.It takes a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack function.


2 Answers

I believe numpy.column_stack should do what you want. Example:

>>> a = np.array((0, 1)) >>> b = np.array((2, 1)) >>> c = np.array((-1, -1)) >>> numpy.column_stack((a,b,c)) array([[ 0,  2, -1],        [ 1,  1, -1]]) 

It is essentially equal to

>>> numpy.vstack((a,b,c)).T 

though. As it says in the documentation.

like image 174
abudis Avatar answered Sep 29 '22 11:09

abudis


I tried the following. Hope this is good enough for what you are doing ?

>>> np.vstack((a,b,c)) array([[ 0,  1],        [ 2,  1],        [-1, -1]]) >>> np.vstack((a,b,c)).T array([[ 0,  2, -1],        [ 1,  1, -1]]) 
like image 45
Pavan Yalamanchili Avatar answered Sep 29 '22 11:09

Pavan Yalamanchili