27

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?

2 Answers 2

61

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't see that one!! I'm afraid the mathesaurus web site is quite outdated. I wish hstack would do the trick without resorting to column_stack but it's good enough.
3

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]])

4 Comments

Yeah, that's good, thanks but I thought that there would be something that could be done along the hstack way (I mean in a more straightforward way. To lower the cognitive load, it would be better to see and concatenate these vectors as column vectors)
a, b and c are row vectors. so it is logical hstack creates a row vector. Having a = np.array(([0], [1])) (and the same with b and c) followed by a hstack would be what you are looking for.
We could do it like this, but we could also just consider that these are all column vectors and it is supposed to be ok as far as numpy is concerned. The problem with this approach is you're already changing the shape of the vectors. In fact, I stumbled upon this when I played with some simple linear algebra in Matlab and doing the same in Python as done there. However in Matlab everything is a 2D-matrix, so we would get the result with a plain [a' b' c']. Unfortunately, using a direct translation np.hstack((a.T, b.T, c.T)) fails indeed
Regarding the comment "To lower the cognitive load, it would be better to see and concatenate these vectors as column vectors)", why not just: np.concatenate([v.reshape((-1,1)) for v in (a, b, c)], axis=1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.