NumPy Tutorial NumPy Statistics NumPy References

NumPy - concatenate() function



The NumPy concatenate() function is used to join a sequence of arrays along the specified axis and returns concatenated array.

Syntax

numpy.concatenate((a1, a2, ...), axis=0, out=None)

Parameters

(a1, a2, ...) Required. Specify the array like objects which need to be concatenated. Objects must have the same shape, except in the dimension corresponding to axis (the first, by default).
axis Optional. Specify the axis along the arrays will be joined. If axis is None, arrays are flattened before use. Default is 0.
out Optional. Specify the destination to place the result. If provided, it must have a shape matching with the returned array.

Return Value

Returns the concatenated array (ndarray).

Example: using concatenate() without axis parameter

In the example below, concatenate() function is used to concatenate arrays Arr1 and Arr2. As the axis parameter is not provided, the concatenation is done on axis=0.

import numpy as np
Arr1 = np.array([[1,10],[2, 20]])
Arr2 = np.array([[3,30],[4, 50]])

cArr = np.concatenate((Arr1, Arr2))
print(cArr)

The output of the above code will be:

[[ 1 10]
 [ 2 20]
 [ 3 30]
 [ 4 50]]

Example: using concatenate() with axis parameter

In this example, Arr1 and Arr2 are concatenated using axis=1.

import numpy as np
Arr1 = np.array([[1,10],[2, 20]])
Arr2 = np.array([[3,30],[4, 50]])

cArr = np.concatenate((Arr1, Arr2), axis=1)
print(cArr)

The output of the above code will be:

[[ 1 10  3 30]
 [ 2 20  4 50]]

Example: using concatenate() with axis=None

When axis=None is used, the array is flattened before concatenating as shown in the example below.

import numpy as np
Arr1 = np.array([[1,10],[2, 20]])
Arr2 = np.array([[3,30],[4, 50]])

cArr = np.concatenate((Arr1, Arr2), axis=None)
print(cArr)

The output of the above code will be:

[ 1 10  2 20  3 30  4 50]

❮ NumPy - Functions