![]() |
VOOZH | about |
NumPy provides flexible and efficient ways to iterate over arrays of any dimensionality. For a one-dimensional array, iterating is straightforward and similar to iterating over a Python list.
Let's understand with the help of an example:
1 2 3 4 5
Explanation:
Let's explore various others ways to iterate over Arrays:
Table of Content
For multidimensional arrays, iteration is performed over the first axis by default. Each iteration yields a one-dimensional sub-array.
[1 2 3] [4 5 6] [7 8 9]
Explanation:
To iterate over individual elements of a 2D array, the array can be flattened using the .flat attribute.
1 2 3 4 5 6 7 8 9
Iteration is similar for arrays with more than two dimensions. In such cases, iteration occurs along the first axis by default.
[[1 2] [3 4]] [[5 6] [7 8]]
Explanation:
The numpy.nditer object offers a various way to iterate over arrays. It allows iteration in different orders and provides better control over the iteration process.
1 2 3 4
We can also specify the order of iteration (row-major order 'C' or column-major order 'F'):
1 3 2 4
For multidimensional arrays, we can use enumerate to access both the index and value during iteration.
Row 0: [10 20] Row 1: [30 40]
When working with arrays of different shapes, Broadcasting allows iteration across combined shapes seamlessly.
1 + 10 = 11 2 + 10 = 12 3 + 10 = 13 1 + 20 = 21 2 + 20 = 22 3 + 20 = 23