0

Let's say I have an numpy array a = [1,2,3,4,5] and another numpy array b = [6,7,8,9,10]. How do I concatenate the arrays and create a numpy array of shape (5,2). I tried both np.row_stack and np.vstack (which do the same thing), but that only results in an np array of shape (2,5). How would I avoid this and get the desired concatenation?

Than you!

2
  • np.vstack((a, b)).T Commented Sep 3, 2017 at 23:39
  • could also just use array function np.array([a,b]).T Commented Sep 3, 2017 at 23:46

2 Answers 2

2

np.vstack is the way to go, you just need an added transposition step afterwards.

c = np.vstack((a, b)).T
print(c)    
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])

print(c.shape)
(5, 2)

As djk47463 mentioned, you can also use the np.array constructor (will delete if they decide to post):

c = np.array([a,b]).T
print(c) 
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])
Sign up to request clarification or add additional context in comments.

1 Comment

Very similar to your answer, hoped you would add it :)
2

Newish np.stack gives more control over the new axis:

In [37]: a = [1,2,3,4,5]
In [38]: b = [6,7,8,9,10]
In [39]: np.stack((a,b), axis=1)
Out[39]: 
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])
In [40]: _.shape
Out[40]: (5, 2)

With the default axis=0, it behaves like np.array, producing a (2,5) array.

vstack docs notes:

This function continues to be supported for backward compatibility, but you should prefer np.concatenate or np.stack. The np.stack function was added in NumPy 1.10.

I think that's overstating the case, but still, stack is one of my favorite new functions. I also recommend looking at the Python code for functions like this. Most end up using concatenate after fiddling with the dimensions of the inputs.

Comments

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.