Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically concatenate two arrays in Python? [duplicate]

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])
like image 739
Eghbal Avatar asked Apr 15 '15 15:04

Eghbal


People also ask

How do I merge two arrays vertically in Python?

vstack() function. The vstack() function is used to stack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). The arrays must have the same shape along all but the first axis.

How do you concatenate multiple arrays in Python?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

How do you stack two arrays named A1 and A2 vertically?

C = vertcat( A1,A2,…,An ) concatenates A1 , A2 , … , An vertically. vertcat is equivalent to using square brackets to vertically concatenate or append arrays. For example, [A; B] is the same as vertcat(A,B) when A and B are compatible arrays.

How do you stack two arrays vertically and horizontally in Python?

hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array. Parameters : tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis.


1 Answers

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

like image 111
Alex Riley Avatar answered Sep 29 '22 09:09

Alex Riley