How to Use np.vstack in NumPy: Stack Arrays Vertically
Use
np.vstack to stack arrays vertically (row-wise) in NumPy. It takes a sequence of arrays with the same number of columns and joins them into one array by adding rows.Syntax
The basic syntax of np.vstack is:
np.vstack(tup): wheretupis a tuple or list of arrays to stack.- All arrays must have the same number of columns (same shape except for the first dimension).
- The result is a new array with rows stacked vertically.
python
np.vstack(tup)
Example
This example shows how to stack two 2D arrays vertically using np.vstack. The arrays must have the same number of columns.
python
import numpy as np array1 = np.array([[1, 2], [3, 4]]) array2 = np.array([[5, 6], [7, 8]]) result = np.vstack((array1, array2)) print(result)
Output
[[1 2]
[3 4]
[5 6]
[7 8]]
Common Pitfalls
Common mistakes when using np.vstack include:
- Trying to stack arrays with different numbers of columns, which causes a
ValueError. - Passing arrays not wrapped in a tuple or list.
- Confusing
vstackwithhstack, which stacks arrays horizontally (column-wise).
python
import numpy as np # Wrong: arrays have different number of columns try: a = np.array([[1, 2]]) b = np.array([[3, 4, 5]]) np.vstack((a, b)) except ValueError as e: print(f"Error: {e}") # Right: arrays have the same number of columns c = np.array([[3, 4]]) result = np.vstack((a, c)) print(result)
Output
Error: all the input array dimensions except for the concatenation axis must match exactly
[[1 2]
[3 4]]
Quick Reference
| Function | Description |
|---|---|
| np.vstack(tup) | Stack arrays vertically (row-wise) |
| np.hstack(tup) | Stack arrays horizontally (column-wise) |
| np.concatenate(tup, axis=0) | General concatenation along rows |
| np.concatenate(tup, axis=1) | General concatenation along columns |
Key Takeaways
np.vstack stacks arrays vertically by adding rows.
All arrays must have the same number of columns to use np.vstack.
Pass arrays as a tuple or list to np.vstack.
np.vstack differs from np.hstack which stacks arrays horizontally.
Mismatched column sizes cause errors with np.vstack.