
When working with NumPy in Python, one of the most common tasks is stacking arrays. The numpy.vstack()
function makes it incredibly easy to stack arrays vertically. But how exactly does it work? In this article, I will dive deep into the details and show you the best example of using numpy.vstack()
.
Understanding numpy.vstack()
The function numpy.vstack()
takes a sequence of arrays and stacks them along the first axis (axis 0). This means it arranges multiple arrays on top of each other, like stacking rows in a matrix.
Here’s the basic syntax:
numpy.vstack(tup)
Where tup
is a sequence of arrays that need to be stacked vertically.
Best Example of Using numpy.vstack()
Let’s see a practical example of how numpy.vstack()
works in Python.
import numpy as np
# Creating two 1D arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Stacking them vertically
result = np.vstack((arr1, arr2))
print(result)
Output:
[[1 2 3]
[4 5 6]]
As you can see, the two 1D arrays are now stacked on top of each other, forming a 2D array.
How numpy.vstack()
Works with 2D Arrays
Stacking 2D arrays works similarly. The function places one array below the other.
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
result = np.vstack((arr1, arr2))
print(result)
Output:
[[1 2]
[3 4]
[5 6]
[7 8]]
Each array is stacked along the first axis, increasing the number of rows.
Key Points to Remember
- All input arrays must have the same number of columns.
- The function can stack both 1D and 2D arrays.
- It increases the number of rows while keeping the columns unchanged.
When to Use numpy.vstack()
?
Here are some common use cases for numpy.vstack()
:
- When combining multiple datasets stored as NumPy arrays.
- When preparing arrays for machine learning models.
- When working with matrices in scientific computing.
Comparison with Other Stacking Functions
NumPy provides other stacking functions, such as numpy.hstack()
and numpy.concatenate()
. Here’s a quick comparison:
Function | Action |
---|---|
numpy.vstack() |
Stacks arrays vertically (row-wise). |
numpy.hstack() |
Stacks arrays horizontally (column-wise). |
numpy.concatenate() |
Allows concatenation along any specified axis. |
Conclusion
Now you know exactly how numpy.vstack()
works in Python and when to use it. It’s a powerful function that simplifies stacking arrays vertically and is widely used in data processing and scientific computing.