π Introduction
Real-world data is rarely one-dimensional.
With NumPy, you can work with multi-dimensional arrays like 2D and 3D structures easily.
π What are Multi-Dimensional Arrays?
Arrays with more than one dimension:
- 1D β List
- 2D β Matrix
- 3D β Collection of matrices
π§ͺ 1. Creating a 2D Array
import numpy as nparr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)
π Output:
[[1 2 3]
[4 5 6]]
π 2. Creating a 3D Array
arr_3d = np.array([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
])print(arr_3d)
π’ 3. Check Dimensions
print(arr_2d.ndim)
print(arr_3d.ndim)
π Output:
2
3
π 4. Accessing Elements
print(arr_2d[0, 1]) # 2
print(arr_3d[1, 0, 1]) # 6
πͺ 5. Slicing Multi-Dimensional Arrays
print(arr_2d[:, 1:])
π Output:
[[2 3]
[5 6]]
β‘ 6. Operations on Multi-Dimensional Arrays
arr = np.array([[1,2],[3,4]])print(arr * 2)
π Output:
[[2 4]
[6 8]]
π¦ 7. Shape of Multi-Dimensional Array
print(arr_3d.shape)
π Example Output:
(2, 2, 2)
β Meaning:
- 2 blocks
- 2 rows
- 2 columns
β‘ Why Use Multi-Dimensional Arrays?
Using NumPy:
- Handle complex datasets
- Work with images & videos
- Perform advanced computations
π¦ Real-World Use Case
# Image representation
image = np.array([[255, 0], [0, 255]])
print(image)
β Used in:
- Image processing
- Machine learning
- AI
π Works with Other Libraries
Multi-dimensional arrays are essential in:
- TensorFlow
- PyTorch
- Pandas
π Summary Table
| Concept | Example |
|---|---|
| 2D Array | [[1,2],[3,4]] |
| 3D Array | [[[…]]] |
| Access | arr[1,0,1] |
| Shape | (2,2,2) |
π§ Pro Tips
- Use
.ndimto check dimensions - Use
.shapeto understand structure - Combine with slicing for powerful operations
π Conclusion
Working with multi-dimensional arrays in NumPy is essential for handling real-world data efficiently.