NumPy Array Joining
In NumPy, joining arrays means combining two or more arrays into a single array.
Instead of manually merging data, NumPy provides fast and efficient functions for this.
This is called Array Joining.
What is Array Joining in NumPy?
Array joining means:
Combining multiple arrays into one larger array.
NumPy provides several methods:
-
concatenate() -
stack() -
hstack() -
vstack() -
dstack()
Why Use Array Joining?
- Combine datasets easily
- Improve data preprocessing
- Useful in machine learning
- Simplifies data manipulation
- Works efficiently with large arrays
1. Using concatenate()
Syntax:
np.concatenate((arr1, arr2))
Example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.concatenate((a, b))
print(result)
Output:
[1 2 3 4 5 6]
2. Joining 2D Arrays
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
result = np.concatenate((a, b))
print(result)
Output:
[[1 2]
[3 4]
[5 6]
[7 8]]
3. Using stack()
Stacking adds a new axis.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.stack((a, b))
print(result)
Output:
[[1 2 3]
[4 5 6]]
4. Horizontal Stack (hstack)
Joins arrays side by side.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.hstack((a, b))
print(result)
Output:
[1 2 3 4 5 6]
5. Vertical Stack (vstack)
Joins arrays vertically.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.vstack((a, b))
print(result)
Output:
[[1 2 3]
[4 5 6]]
6. Depth Stack (dstack)
Stacks arrays along depth (3D axis).
a = np.array([1, 2])
b = np.array([3, 4])
result = np.dstack((a, b))
print(result)
Output:
[[[1 3]
[2 4]]]
Visual Understanding
| Function | Behavior |
|---|---|
| concatenate | Join without new axis |
| stack | Adds new axis |
| hstack | Horizontal join |
| vstack | Vertical join |
| dstack | Depth-wise join |
Real-World Use Cases
Array joining is used in:
- Merging datasets
- Image processing
- Machine learning pipelines
- Feature engineering
- Database operations
Example: Combining Features
X1 = np.array([1, 2, 3])
X2 = np.array([4, 5, 6])
X = np.concatenate((X1, X2))
✔ Combines features into one dataset
Example: Image Channels
image = np.dstack((red, green, blue))
✔ Combines RGB channels
Advantages of NumPy Joining
- Fast execution
- Flexible combining options
- Works with multi-dimensional arrays
- Essential for ML workflows
- Simple and readable syntax
Summary
NumPy array joining allows you to combine multiple arrays using functions like concatenate, stack, hstack, vstack, and dstack.
It is a core feature of NumPy and widely used in data processing and machine learning with Python.
Conclusion
Mastering array joining helps you efficiently combine and organize data, making it essential for data science, AI, and numerical computing tasks.


0 Comments