30
The easiest way to concatenate arrays in Python is to use the numpy.concatenate function, which uses the following syntax:
numpy.concatenate((a1, a2, ….), axis = 0)
where:
- a1, a2 …: The sequence of arrays
- axis: The axis along which the arrays will be joined. Default is 0.
This tutorial provides several examples of how to use this function in practice.
Example 1: Concatenate Two Arrays
The following code shows how to concatenate two 1-dimensional arrays:
import numpy as np #create two arrays arr1 = np.array([1, 2, 3, 4, 5]) arr2 = np.array([6, 7, 8]) #concatentate the two arrays np.concatenate((arr1, arr2)) [1, 2, 3, 4, 5, 6, 7, 8]
The following code shows how to concatenate two 2-dimensional arrays:
import numpy as np #create two arrays arr1 = np.array([[3, 5], [9, 9], [12, 15]]) arr2 = np.array([[4, 0]]) #concatentate the two arrays np.concatenate((arr1, arr2), axis=0) array([[3, 5], [9, 9], [12, 15], [4, 0]]) #concatentate the two arrays and flatten the result np.concatenate((arr1, arr2), axis=None) array([3, 5, 9, 9, 12, 15, 4, 0])
Example 2: Concatenate More Than Two Arrays
We can use similar code to concatenate more than two arrays:
import numpy as np #create four arrays arr1 = np.array([[3, 5], [9, 9], [12, 15]]) arr2 = np.array([[4, 0]]) arr3 = np.array([[1, 1]]) arr4 = np.array([[8, 8]]) #concatentate all the arrays np.concatenate((arr1, arr2, arr3, arr4), axis=0) array([[3, 5], [9, 9], [12, 15], [4, 0], [1, 1], [8, 8]]) #concatentate all the arrays and flatten the result np.concatenate((arr1, arr2, arr3, arr4), axis=None) array([3, 5, 9, 9, 12, 15, 4, 0, 1, 1, 8, 8])
Additional Resources
The following tutorials explain how to perform similar operations in NumPy:
How to Create a Pandas DataFrame from a NumPy Array
How to Add a Numpy Array to a Pandas DataFrame