Multi-Dimensional NumPy Arrays (Beginner Guide) 🚀
In this tutorial, you’ll learn how NumPy handles multiple dimensions using simple and practical examples.
🔹 What is Dimension?
1D → [1 2 3 4] 2D → [[1 2 3 4]] 3D → [[[1 2 3 4]]]
👉 More brackets = more dimensions
🔹 Creating a Basic Array
import numpy as np l=[1,2,3,4] a=np.array(l) print(a)
Output:
[1 2 3 4]
🔹 Checking Dimension (.ndim)
.ndim tells how many dimensions an array has.
l=[1,2,3,4] a=np.array(l) print(a) print(a.ndim) print(type(a.ndim))
Output:
[1 2 3 4] 1 <class 'int'>
👉 Means it is a 1D array
🔹 Simple 2D Array
l=[1,2,3,4] a=np.array([l]) print(a) print(a.ndim)
Output:
[[1 2 3 4]] 2
👉 Two brackets → 2D array
Real-Life Idea: Think of this as a single row table.
🔹 Multiple Values 2D Array
l=[1,2,3,4] a=np.array([l,l]) print(a) print(a.ndim)
Output:
[[1 2 3 4] [1 2 3 4]] 2
👉 This is like a matrix (rows & columns)
⚠️ Note: All rows must have same number of elements
🔹 3D Array Example
a=np.array([[[1,2,3,4],[10,2,3,4],[1,2,30,4],[1,20,3,4]]]) print(a) print(a.ndim)
Output:
[[[ 1 2 3 4] [10 2 3 4] [ 1 2 30 4] [ 1 20 3 4]]] 3
👉 3D arrays are like multiple tables stacked together
🔹 Creating Higher Dimensions (ndmin)
ndmin forces NumPy to create an array with minimum dimensions.
l=[1,2,3,4] a=np.array(l, ndmin=10) print(a) print(a.ndim) print(type(a.ndim))
Output (shortened view):
[[[[[[[[[[1 2 3 4]]]]]]]]]] 10 <class 'int'>
👉 NumPy adds extra brackets to reach required dimension
⚠️ Note: Maximum allowed dimensions = 64
🔹 Important Functions Explained
- np.array() → Converts list into NumPy array
- .ndim → Returns number of dimensions
- ndmin → Forces minimum dimensions
🔹 Beginner Tips 💡
- Start with 1D → then move to 2D
- Use brackets carefully (they define dimension)
- Always check dimension using .ndim
🔹 Common Mistakes ⚠️
- Unequal list sizes in 2D → causes errors
- Confusing brackets → wrong dimensions
- Forgetting import numpy
🔚 Final Thoughts
Understanding dimensions is key to mastering NumPy.
- 1D → simple data
- 2D → tables
- 3D → multiple tables