vstack() is a convenience wrapper: it treats each input as a row, promoting a 1D array to a single row if needed, and stacks them on top of each other, requiring all inputs to have the same number of columns. For already-2D arrays, np.vstack((a, b)) is exactly equivalent to np.concatenate((a, b), axis=0), but vstack()'s name communicates the specific, common 'stack rows' intent more directly than a generic axis argument does.
1Understanding np.vstack()
vstack() is a convenience wrapper: it treats each input as a row, promoting a 1D array to a single row if needed, and stacks them on top of each other, requiring all inputs to have the same number of columns. For already-2D arrays, np.vstack((a, b)) is exactly equivalent to np.concatenate((a, b), axis=0), but vstack()'s name communicates the specific, common 'stack rows' intent more directly than a generic axis argument does.
vstack() is especially convenient for combining several 1D arrays into rows of a 2D matrix, since it automatically treats each 1D input as one row, something concatenate() alone doesn't do without first reshaping them.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.vstack((a, b)))2Practical Example
Here is a real-world application of np.vstack() showing how it is used in production NumPy code.
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
print(np.vstack((a, b)))3Best Practices
Follow these guidelines when working with np.vstack():
1. Use vstack() for the common case of stacking arrays as new rows, instead of the more generic np.concatenate(..., axis=0)
2. Ensure every input array has the same number of columns, the same size along axis 1, before calling vstack()
3. Use vstack() to combine several 1D arrays into a single 2D matrix, one row per input, without manually reshaping each one first
Tip: vstack() is especially convenient for combining several 1D arrays into rows of a 2D matrix, since it automatically treats each 1D input as one row, something concatenate() alone doesn't do without first reshaping them.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.vstack((a, b)))