π Introduction
Looping through data is a common task in programming.
With NumPy, you can iterate arrays efficiently using built-in methods.
π Why Iteration Matters?
Iteration helps you:
- Process each element
- Apply transformations
- Analyze datasets
π§ͺ 1. Iterating 1D Array
import numpy as nparr = np.array([10, 20, 30])for x in arr:
print(x)
π 2. Iterating 2D Array
arr = np.array([[1, 2], [3, 4]])for row in arr:
for item in row:
print(item)
π 3. Using nditer() (Efficient Way)
arr = np.array([[1, 2], [3, 4]])for x in np.nditer(arr):
print(x)
β Flattens and iterates efficiently
β‘ 4. Iterating with Index (ndenumerate())
for index, value in np.ndenumerate(arr):
print(index, value)
π Output:
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
π 5. Iterating 3D Arrays
arr = np.array([
[[1,2],[3,4]],
[[5,6],[7,8]]
])for x in np.nditer(arr):
print(x)
β οΈ Important Note
Although iteration is possible, avoid loops when possible.
π Use vectorized operations for better performance.
β‘ Why Use NumPy Iteration Tools?
Using NumPy:
- Efficient iteration
- Works with multi-dimensional arrays
- More control than basic loops
π¦ Real-World Use Case
data = np.array([10, 20, 30])for i, val in enumerate(data):
print(f"Index {i}: {val}")
β Used in:
- Data processing
- Debugging
- Transformations
π Works with Other Libraries
Iteration is used in:
- Pandas
- TensorFlow
- Scikit-learn
π Summary Table
| Method | Description |
|---|---|
| for loop | Basic iteration |
| nditer() | Efficient iteration |
| ndenumerate() | Index + value |
π§ Pro Tips
- Prefer vectorization over loops
- Use
nditer()for large arrays - Use
ndenumerate()for indexing
π Conclusion
Iteration in NumPy is flexible, but should be used wisely for best performance.