NumPy Array Join
Joining arrays in NumPy combines two or more separate arrays into one, either by concatenating them end-to-end or stacking them along a brand-new axis.
Why Combine Arrays?
In real analysis work, data rarely arrives in one tidy array. You might load sensor readings in daily batches, collect results from several experiments, or build a matrix one row at a time. NumPy's join functions let you take these separate pieces and merge them into a single array so the rest of your pipeline can treat the data uniformly.
np.concatenate(): The General-Purpose Joiner
np.concatenate() is the most flexible joining function. It takes a sequence of arrays and an axis argument, then glues the arrays together along that axis. For 1D arrays there is only one axis (0), but for 2D and higher-dimensional arrays you choose whether to join rows (axis=0) or columns (axis=1). Every array being joined must have the same shape along every axis except the one you are joining on.
Example
import numpy as np
# Joining two 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.concatenate((arr1, arr2))
print(result)
# [1 2 3 4 5 6]
# Joining two 2D arrays along axis 1 (columns)
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[5, 6], [7, 8]])
result2 = np.concatenate((mat1, mat2), axis=1)
print(result2)
# [[1 2 5 6]
# [3 4 7 8]]Stacking with stack(), hstack(), and vstack()
While concatenate() joins arrays along an existing axis, np.stack() joins them along a brand-new axis, increasing the dimensionality of the result. NumPy also ships convenience wrappers built on top of stacking logic: hstack() joins arrays horizontally (side by side, along columns), and vstack() joins them vertically (on top of each other, along rows). These read more naturally than remembering the right axis number for concatenate().
- np.stack(arrays, axis=0) — creates a new axis and stacks arrays along it, so the result has one more dimension than the inputs.
- np.hstack(arrays) — stacks arrays horizontally; equivalent to concatenate along axis=1 for 2D arrays (or axis=0 for 1D arrays).
- np.vstack(arrays) — stacks arrays vertically; equivalent to concatenate along axis=0.
- np.dstack(arrays) — stacks arrays along the third axis (depth), useful for building image-like data with channels.
Example
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# hstack places them side by side
print(np.hstack((arr1, arr2)))
# [1 2 3 4 5 6]
# vstack stacks them as new rows
print(np.vstack((arr1, arr2)))
# [[1 2 3]
# [4 5 6]]Example
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# stack() adds a brand-new axis
stacked = np.stack((arr1, arr2), axis=0)
print(stacked)
print(stacked.shape)
# [[1 2 3]
# [4 5 6]]
# (2, 3)
stacked_axis1 = np.stack((arr1, arr2), axis=1)
print(stacked_axis1)
# [[1 4]
# [2 5]
# [3 6]]Exercise: NumPy Array Join
Which NumPy function joins two or more arrays along an existing axis?