NumPy Array Iterating
🔁 NumPy Array Iteration (Complete Guide with Examples)
Iterating through NumPy arrays means accessing elements one-by-one using loops.
NumPy provides efficient ways to iterate through 1D, 2D, 3D arrays, including vectorized methods.
✅ 1. Iterating a 1D Array
Output:
✅ 2. Iterating a 2D Array (Row by Row)
Output:
✅ 3. Iterating 2D Array Element-by-Element
Output:
✅ 4. Iterating a 3D Array
🔹 Iterating Inside 3D
🚀 Better Way: np.nditer()
nditer() allows fast iteration over any dimension array.
Output:
✨ Iterating with Data Type Conversion
🔁 Iterating with Index using ndenumerate()
Useful when you need index + value.
Output:
Summary Table
| Method | Best For | Example |
|---|---|---|
Simple for |
1D arrays | for x in arr |
| Nested Loop | 2D/3D arrays | for row in arr: |
np.nditer() |
Fast iteration for any dimension | for x in np.nditer(arr) |
np.ndenumerate() |
Iteration with index | for idx, val in np.ndenumerate(arr) |
