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])
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.
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.
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.
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.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With