NumPy vstack()
The `numpy.vstack()` function is used to stack arrays in sequence vertically (row-wise). It joins arrays along the first axis, making it useful for combining arrays with the same number of columns.
Usage
The `vstack()` function is typically used when you want to merge multiple arrays into a single array by stacking them on top of each other. This function requires that the arrays have the same shape along all but the first axis.
numpy.vstack((array1, array2, ...))
In this syntax, `vstack()` takes a tuple of arrays and returns a single array by stacking the input arrays vertically.
Examples
1. Basic Vertical Stacking
import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
result = np.vstack((array1, array2))
print(result)
This example stacks two 1-D arrays vertically, resulting in a 2x3 array.
2. Stacking 2-D Arrays
import numpy as np
array1 = np.array([[1, 2, 3], [4, 5, 6]])
array2 = np.array([[7, 8, 9], [10, 11, 12]])
result = np.vstack((array1, array2))
print(result)
In this example, two 2x3 arrays are stacked vertically to produce a 4x3 array.
3. Stacking Arrays with More Dimensions
import numpy as np
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
result = np.vstack((array1, array2, array1))
print(result)
Here, two 2x2 arrays are stacked with an additional copy of the first array, resulting in a 6x2 array.
Tips and Best Practices
- Ensure Compatibility: Make sure all arrays have the same shape except along the first axis before using `vstack()`. If this requirement is not met, a `ValueError` will be raised.
- Use for Homogeneous Data: Ideal for stacking arrays of the same data type to avoid type coercion.
- Check Dimensions: Use `array.ndim` to confirm the dimensionality before stacking to prevent unexpected results.
- Performance Considerations: When stacking large arrays, consider the memory implications and optimize array sizes where possible.
- Function Equivalence: `vstack()` is equivalent to using `np.concatenate()` with `axis=0`, which could be useful for users familiar with the `concatenate` function.
- Alternatives and Aliases: For horizontal stacking, consider using `hstack()`. Also, note that `vstack()` can be accessed using `np.row_stack()`, which is an alias for `vstack()` and might be encountered in different codebases.