Contents
NumPy – Concatenate Arrays
To concatenate arrays in NumPy, call numpy.concatenate() function, pass tuple of arrays to be concatenated, and the axis along which concatenation must happen, as arguments.
The syntax to concatenate array1 and array2 numpy arrays is
numpy.concatenate((array1, array2, ...), axis=0)
By default, the arrays are concatenated along axis=0. We can override this behaviour by passing a specific value for axis parameter.
Note: The arrays to be concatenated must have the same shape along all but the specified axis.
Examples
1. Concatenate arrays along default axis (=0)
In the following program, we take two numpy arrays. of shape (3, 2) and (4, 2). We concatenate these two array along default axis.
Python Program
import numpy as np
array1 = np.array([[1, 2], [3, 4], [5, 6]])
array2 = np.array([[7, 8], [9, 10], [11, 12]])
output = np.concatenate((array1, array2))
print(output)
Run Code CopyOutput
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
For the two arrays, the length of the arrays along axis=0 is different, but the length of the arrays along axis=1 is same which satisfies the required condition for concatenation.
2. Concatenate arrays along axis=1
In the following program, we take a numpy array of shape (3, 4), and (3, 2), and concatenate them along axis=1.
Python Program
import numpy as np
array1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
array2 = np.array([[13, 14], [15, 16], [17, 18]])
output = np.concatenate((array1, array2), axis=1)
print(output)
Run Code CopyOutput
[[ 1 2 3 4 13 14]
[ 5 6 7 8 15 16]
[ 9 10 11 12 17 18]]
Summary
In this NumPy Tutorial, we learned how to concatenate numpy arrays in Python using numpy.concatenate() function.