Stacking Arrays
Stacking involves joining a sequence of arrays along a new axis, either vertically (vstack
) or horizontally (hstack
).
Code Example:
import numpy as np
# Creating two 2D arrays
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
# Vertically stacking arrays a and b
vstacked = np.vstack((a, b))
# Horizontally stacking arrays a and b
hstacked = np.hstack((a, b))
print("Vertically Stacked:\n", vstacked)
print("\nHorizontally Stacked:\n", hstacked)
PythonOutput
Vertically Stacked:
[[1 2]
[3 4]
[5 6]
[7 8]]
Horizontally Stacked:
[[1 2 5 6]
[3 4 7 8]]
PythonExplanation:
np.vstack((a, b))
stacks the arraysa
andb
vertically, addingb
undera
.np.hstack((a, b))
stacks the arraysa
andb
horizontally, placingb
to the right ofa
.