We use np.concatenate() to join two or more arrays into one. It helps combine data from different sources into a single array.
np.concatenate() for joining arrays in NumPy
import numpy as np # Define arrays to join array1 = np.array([...]) array2 = np.array([...]) # Join arrays along an axis joined_array = np.concatenate((array1, array2), axis=0)
The arrays must have the same shape except in the dimension you join on.
The axis parameter decides if you join rows (axis=0) or columns (axis=1).
import numpy as np # Example 1: Join 1D arrays array1 = np.array([1, 2, 3]) array2 = np.array([4, 5]) result = np.concatenate((array1, array2)) print(result)
import numpy as np # Example 2: Join 2D arrays along rows (axis=0) array1 = np.array([[1, 2], [3, 4]]) array2 = np.array([[5, 6]]) result = np.concatenate((array1, array2), axis=0) print(result)
import numpy as np # Example 3: Join 2D arrays along columns (axis=1) array1 = np.array([[1, 2], [3, 4]]) array2 = np.array([[5], [6]]) result = np.concatenate((array1, array2), axis=1) print(result)
import numpy as np # Example 4: Edge case - empty array array1 = np.array([1, 2, 3]) array2 = np.array([]) result = np.concatenate((array1, array2)) print(result)
This program creates two arrays and joins them by adding rows. It prints the arrays before and after joining so you can see the change.
import numpy as np # Create two 2D arrays array1 = np.array([[10, 20], [30, 40]]) array2 = np.array([[50, 60]]) print("Array 1 before joining:") print(array1) print("Array 2 before joining:") print(array2) # Join arrays along rows (axis=0) joined_array = np.concatenate((array1, array2), axis=0) print("\nJoined array after np.concatenate along axis=0:") print(joined_array)
Time complexity: Joining arrays takes time proportional to the total size of the output array.
Space complexity: A new array is created, so space grows with the combined size.
Common mistake: Trying to join arrays with mismatched shapes on non-joining axes causes errors.
Use np.concatenate() when you want to join arrays along an existing axis. For adding new dimensions, consider np.stack().
np.concatenate() joins arrays along a chosen axis.
Arrays must match in shape except on the joining axis.
It creates a new combined array without changing the originals.