Joining NumPy Arrays
Joining in NumPy means combining the elements of two or more arrays into a single array.
Unlike SQL, where tables are joined based on keys, NumPy joins arrays along specified axes.
To join arrays, we use the concatenate() function. This function takes a sequence of arrays to join and an optional axis argument. If the axis isn’t provided, it defaults to 0.
Program:
Join Two 1-D Arrays
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.concatenate((arr1, arr2))
print(result)
Output:
Program:
Join Two 2-D Arrays Along Columns (axis=1)
import numpy as np
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
result = np.concatenate((arr1, arr2), axis=1)
print(result)
Output:
Joining Arrays Using Stack Functions
Stacking is similar to concatenation, but it joins arrays along a new axis.
Using the stack() function, we can combine arrays along a new dimension. By default, stacking is done along axis 0 unless specified otherwise.
Program:
Stack Two 1-D Arrays Along a New Axis
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.stack((arr1, arr2), axis=1)
print(result)
Output:
Stacking Arrays Along Different Axes
NumPy provides specific helper functions for stacking along different axes:
1. Stacking Along Rows (hstack)
Stacks arrays horizontally (along columns).
Program:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.hstack((arr1, arr2))
print(result)
Output:
2. Stacking Along Columns (vstack)
Stacks arrays vertically (along rows).
Program:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.vstack((arr1, arr2))
print(result)
Output:
3. Stacking Along Depth (dstack)
Stacks arrays along the third axis (depth).
Program:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
result = np.dstack((arr1, arr2))
print(result)