Stacking Arrays: np.vstack(), np.hstack(), & np.concatenate() Combining multiple datasets, merging feature matrices with target labels, and assembling image tiles are fundamental tasks in numerical data pipelines.
NumPy provides specialized functions to combine arrays along existing or new axes:
np.concatenate(): The generalized foundational routine.np.vstack(): Vertical stacking (row-wise / along axis 0).np.hstack(): Horizontal stacking (column-wise / along axis 1). Click to ZoomNumPy Reshaping and Stacking np.concatenate((a1, a2, ...), axis=0) joins a sequence of arrays along an existing axis . All input arrays must have the exact same shape, except in the dimension corresponding to axis:
1 import numpy as np
2
3 A = np . array ( [ [ 1 , 2 ] ,
4 [ 3 , 4 ] ] )
5
6 B = np . array ( [ [ 5 , 6 ] ,
7 [ 7 , 8 ] ] )
8
9 # Concatenate vertically along axis 0 (rows)
10 concat_axis0 = np . concatenate ( ( A , B ) , axis = 0 )
11 print ( "Concatenate axis 0 (Shape:" , concat_axis0 . shape , " ) :
12 " , concat_axis0 )
13
14 # Concatenate horizontally along axis 1 (columns)
15 concat_axis1 = np . concatenate ( ( A , B ) , axis = 1 )
16 print ( "
17 Concatenate axis 1 ( Shape : ", concat_axis1.shape, " ) :
18 " , concat_axis1 )
Output:
1 Concatenate axis 0 (Shape: (4, 2) ):
2 [[1 2]
3 [3 4]
4 [5 6]
5 [7 8]]
6
7 Concatenate axis 1 (Shape: (2, 4) ):
8 [[1 2 5 6]
9 [3 4 7 8]]
np.vstack() stacks arrays vertically (row on top of row). For 2D arrays, this is equivalent to np.concatenate(..., axis=0).
Crucially, for 1D arrays , np.vstack() treats them as rows of shape (1, N) and stacks them into a 2D matrix:
1 x = np . array ( [ 1 , 2 , 3 ] )
2 y = np . array ( [ 4 , 5 , 6 ] )
3
4 # Stacking 1D arrays vertically creates a 2D array of shape (2, 3)
5 v_stacked = np . vstack ( ( x , y ) )
6 print ( "vstack 1D arrays :
7 " , v_stacked )
8 print ( "Shape:" , v_stacked . shape )
Output:
1 vstack 1D arrays:
2 [[1 2 3]
3 [4 5 6]]
4 Shape: (2, 3)
np.hstack() stacks arrays horizontally (column next to column).
For 2D arrays , it stacks along columns (equivalent to np.concatenate(..., axis=1)). For 1D arrays , it concatenates them end-to-end into a longer 1D array: 1 # For 1D arrays: concatenates along the single axis
2 h_1d = np . hstack ( ( x , y ) )
3 print ( "hstack 1D arrays:" , h_1d ) # [1 2 3 4 5 6]
4 print ( "Shape:" , h_1d . shape ) # (6,)
5
6 # For 2D arrays: stacks side-by-side
7 M1 = np . ones ( ( 2 , 2 ) )
8 M2 = np . zeros ( ( 2 , 3 ) )
9 h_2d = np . hstack ( ( M1 , M2 ) )
10 print ( "
11 hstack 2D arrays :
12 " , h_2d )
13 print ( "Shape:" , h_2d . shape ) # (2, 5)
4. Dimensional Alignment Rules and Common Pitfalls When concatenating or stacking arrays, shape mismatches along non-concatenating axes raise ValueError:
1 A = np . ones ( ( 3 , 4 ) )
2 B = np . ones ( ( 2 , 5 ) )
3
4 # Attempting to vstack A (4 cols) and B (5 cols) will fail:
5 try :
6 np . vstack ( ( A , B ) )
7 except ValueError as e :
8 print ( "Alignment Error:" , e )
9 # Output: all the input array dimensions for the concatenation
10 # axis must match exactly, but along dimension 1,
11 # the array at index 0 has size 4 and the array at index 1 has size 5
Interactive Quiz • Knowledge Check
Multiple Choice Questions What is the required argument format for arrays passed to np.concatenate()?
A Individual positional arguments: np.concatenate(a, b, c)
B A tuple or list sequence: np.concatenate((a, b, c))
C A dictionary of arrays
D A single string specifying the variable names
What is the resulting shape when executing np.vstack((np.array([1, 2, 3]), np.array([4, 5, 6])))?
A (6,)
B (2, 3)
C (3, 2)
D (1, 6)
What is the resulting shape when executing np.hstack((np.array([1, 2, 3]), np.array([4, 5, 6])))?
A (6,)
B (2, 3)
C (1, 6)
D (3, 2)
Given 2D arrays A of shape (3, 4) and B of shape (3, 2), which function will successfully combine them?
A np.vstack((A, B))
B np.hstack((A, B))
C np.concatenate((A, B), axis=0)
D None; their shapes are incompatible
How does np.concatenate((a, b), axis=None) behave?
A It raises a ValueError
B It flattens all input arrays before concatenating them into a 1D array
C It stacks them along a newly created dimension
D It performs matrix multiplication