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