17

Assume I have many numpy array:

a = ([1,2,3,4,5])
b = ([2,3,4,5,6])
c = ([3,4,5,6,7])

and I want to generate a new 2-D array:

d = ([[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7]])

What should I code? I tried used:

d = np.concatenate((a,b),axis=0)
d = np.concatenate((d,c),axis=0)

It returns:

d = ([1,2,3,4,5,2,3,4,5,6,3,4,5,6,7])
2
  • 1
    Try numpy.vstack : np.vstack((a,b,c)). Commented Jun 13, 2017 at 9:43
  • 3
    Also np.array([a,b,c]) and np.stack([a,b,c]). Both concatenate on a new dimension. Commented Jun 13, 2017 at 10:51

1 Answer 1

28

As mentioned in the comments you could just use the np.array function:

>>> import numpy as np
>>> a = ([1,2,3,4,5])
>>> b = ([2,3,4,5,6])
>>> c = ([3,4,5,6,7])

>>> np.array([a, b, c])
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7]])

In the general case that you want to stack based on a "not-yet-existing" dimension, you can also use np.stack:

>>> np.stack([a, b, c], axis=0)
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 6],
       [3, 4, 5, 6, 7]])

>>> np.stack([a, b, c], axis=1)  # not what you want, this is only to show what is possible
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6],
       [5, 6, 7]])
Sign up to request clarification or add additional context in comments.

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.