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?
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.
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.
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.
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.
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With