๐ 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.