![]() |
VOOZH | about |
Joining NumPy arrays means combining multiple arrays into one larger array. For example, joining two arrays [1, 2] and [3, 4] results in a combined array [1, 2, 3, 4]. Let’s explore some common ways to join arrays using NumPy.
numpy.concatenate() joins two or more arrays along an existing axis without adding new dimensions. It is fast and efficient for straightforward array joining.
[1 2 3 4]
This code combines them into one longer list [1, 2, 3, 4] using NumPy’s concatenate function which just sticks the arrays together end to end.
numpy.hstack(), numpy.vstack() and numpy.dstack() are convenient wrappers around concatenate for stacking arrays horizontally, vertically or depth-wise making code more readable and expressive.
np.hstack: [1 2 3 4 5 6] np.vstack: [[1 2 3] [4 5 6]] np.dstack: [[[1 4] [2 5] [3 6]]]
numpy.stack() joins arrays along a new axis, increasing the dimensionality. It is useful when you want to combine arrays but keep them separated along a new dimension.
[[1 5] [2 6] [3 7] [4 8]]
stack with axis=1 makes the code combines them by pairing elements side-by-side into rows, creating a 2D array where each row contains one element from each array.
numpy.block() builds arrays from nested blocks like assembling matrices from smaller sub-arrays. It provides flexible and powerful ways to create complex array layouts.
[[1 1 2 2 2] [1 1 2 2 2] [3 3 4 4 4] [3 3 4 4 4] [3 3 4 4 4]]
Four small arrays are arranged as blocks b1 and b2 side by side on top, b3 and b4 side by side below. np.block joins them into one large array preserving this layout.