0
0
NumPydata~5 mins

np.concatenate() for joining arrays in NumPy

Choose your learning style9 modes available
Introduction

We use np.concatenate() to join two or more arrays into one. It helps combine data from different sources into a single array.

You have separate lists of numbers and want to analyze them together.
You collected data in parts and want to merge them for a report.
You want to add new rows or columns to an existing dataset.
You want to combine results from different experiments into one array.
Syntax
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).

Examples
Joins two 1D arrays into one longer array.
NumPy
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)
Joins arrays by adding rows. The number of columns must match.
NumPy
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)
Joins arrays by adding columns. The number of rows must match.
NumPy
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)
Joining with an empty array returns the original array unchanged.
NumPy
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)
Sample Program

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.

NumPy
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)
OutputSuccess
Important Notes

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().

Summary

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.