Latest Code Tutorials

np.concatenate: How to Join Numpy Array in Python

The np.concatenate() is a numpy library function that joins two numpy arrays into a single numpy array. There are two types of concatenating the arrays. One is by concatenating using the axis 0, that is, by adding the second array at the end of the first array. Then another one is by concatenating the first array and second array by columns.

The columns of the second array will be joined at the end of the columns of the first array.


numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting="same_kind")


( a1, a2, …): This is the sequence of the arrays that we want to concatenate. 

axis: It is the axis along which the arrays will be joined. By default, it is 0. It concatenates row-wise. If the axis is 1, then it is concatenated column-wise. 

out: If this out is used, the shape must be correct. 

dtype: The dtype stands for the data type. We can specify the data type in the dtype argument. The output array will have the data type provided in this argument. If nothing is provided, then it takes the data type as None

casting: The casting consists of several castings – no, equiv, safe, same_kind, unsafe. Same_kind is set as the default.

Python program for concatenating two arrays using np.concatenate

# import Numpy as np
import numpy as np

# creating an numpy array named arr1
arr1 = np.array([1, 2, 3])

# creating an numpy array named arr2
arr2 = np.array([4, 5, 6])

# concatenating arr1 and arr2
res = np.concatenate((arr1, arr2))


[1 2 3 4 5 6]

In this program, we imported numpy for working with numerical data. Then, we created two numpy arrays named arr1 and arr2. Then we concatenated using a np.concatenate() function.

The np.concatenate() function concatenates arr1 with arr2. Since no other arguments are passed, it will consider the default arguments.

Axis will be considered as 0. Both axis results in the same output in a single dimensional array, but in multi-dimensional arrays, the axis changes its result. In this program, the elements are added by rows.

Let’s see another example.

# Import Numpy as np
import numpy as np

# creating an numpy array named arr1
arr1 = np.array([[8, 7], [6, 5]])

# creating an numpy array named arr2
arr2 = np.array([[4, 3], [2, 1]])

# concatenating arr1 and arr2
res = np.concatenate((arr1, arr2), axis=1)


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

In this program, we used the axis as 1. The program will concatenate the first row of the second array with the first row of the first array. Hence the columns from the first array are combined with the columns of the second array.

That’s it for this tutorial.

Related posts




Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.