14

I want to concatenate two arrays vertically in Python using the NumPy package:

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

I want something like this:

c = array([[1,2,3,4],[5,6,7,8]])

How we can do that using the concatenate function? I checked these two functions but the results are the same:

c = concatenate((a,b),axis=0)
# or
c = concatenate((a,b),axis=1)

We have this in both of these functions:

c = array([1,2,3,4,5,6,7,8])
0

4 Answers 4

16

The problem is that both a and b are 1D arrays and so there's only one axis to join them on.

Instead, you can use vstack (v for vertical):

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

Also, row_stack is an alias of the vstack function:

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

It's also worth noting that multiple arrays of the same length can be stacked at once. For instance, np.vstack((a,b,x,y)) would have four rows.

Under the hood, vstack works by making sure that each array has at least two dimensions (using atleast_2D) and then calling concatenate to join these arrays on the first axis (axis=0).

6

Use np.vstack:

In [4]:

import numpy as np
a = np.array([1,2,3,4])
b = np.array([5,6,7,8])
c = np.vstack((a,b))
c
Out[4]:
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

In [5]:

d = np.array ([[1,2,3,4],[5,6,7,8]])
d
​
Out[5]:
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
In [6]:

np.equal(c,d)
Out[6]:
array([[ True,  True,  True,  True],
       [ True,  True,  True,  True]], dtype=bool)
6

Maybe it's not a good solution, but it's simple way to makes your code works, just add reshape:

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

c = concatenate((a,b),axis=0).reshape((2,4))

print c

out:

[[1 2 3 4]
 [5 6 7 8]]

In general if you have more than 2 arrays with the same length:

reshape((number_of_arrays, length_of_array))
3

To use concatenate, you need to make a and b 2D arrays instead of 1D, as in

c = concatenate((atleast_2d(a), atleast_2d(b)))

Alternatively, you can simply do

c = array((a,b))
2
  • Thank you for answer. How we can horizontally concatenate using array? Is it only for vertically concatenation?
    – Eghbal
    Commented Apr 15, 2015 at 15:48
  • @user2991243 You can use the axis parameter to control which axis to concatenate, and it defaults to 0.
    – Ying Xiong
    Commented Apr 15, 2015 at 19:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.