Numpy Terating Over Array
The NumPy iterator object numpy.nditer provides a flexible way to access one or more array elements.
The most basic task of the iterator is to access array elements.
Next, we use the arange() function to create a 2X3 array and iterate over it using nditer.
## Example
import numpy as np a = np.arange(6).reshape(2,3)print('Original array is:')print(a)print('n')print('Iterating output elements:')for x in np.nditer(a): print(x, end=", ")print('n')
The output is:
Original array is:[ ]Iterating output elements:0, 1, 2, 3, 4, 5,
The above example does not use standard C or Fortran order; the chosen order is consistent with the array's memory layout, which is done to improve access efficiency. The default is row-major order (or C-order).
This reflects that by default we only need to access each element without considering its specific order. We can see this by iterating over the transpose of the above array and comparing it with the copy method that accesses the array transpose in C order, as shown in the following example:
## Example
import numpy as np a = np.arange(6).reshape(2,3)for x in np.nditer(a.T): print(x, end=", ")print('n')for x in np.nditer(a.T.copy(order='C')): print(x, end=", ")print('n')
The output is:
0, 1, 2, 3, 4, 5, 0, 3, 1, 4, 2, 5,
From the above example, we can see that the traversal order of a and a.T is the same, which means their storage order in memory is also the same. However, the traversal result of a.T.copy(order = 'C') is different, because its storage method is different from the first two. The default is row-wise access.
### Controlling Traversal Order
* `for x in np.nditer(a, order='F'):` Fortran order, i.e., column-major order;
* `for x in np.nditer(a.T, order='C'):` C order, i.e., row-major order;
## Example
import numpy as np a = np.arange(0,60,5)a = a.reshape(3,4)print('Original array is:')print(a)print('n')print('Transpose of original array:')b = a.T print(b)print('n')print('Sorted in C-style order:')c = b.copy(order='C')print(c)for x in np.nditer(c): print(x, end=", ")print('n')print('Sorted in F-style order:')c = b.copy(order='F')print(c)for x in np.nditer(c): print(x, end=", ")
The output is:
Original array is:[ ]Transpose of original array:[ ]Sorted in C-style order:[ ]0, 20, 40, 5, 25, 45, 10, 30, 50, 15, 35, 55, Sorted in F-style order:[ ]0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55,
We can explicitly set to force the nditer object to use a certain order:
## Example
import numpy as np a = np.arange(0,60,5)a = a.reshape(3,4)print('Original array is:')print(a)print('n')print('Sorted in C-style order:')for x in np.nditer(a, order = 'C'): print(x, end=", ")print('n')print('Sorted in F-style order:')for x in np.nditer(a, order = 'F'): print(x, end=", ")
The output is:
Original array is:[ ]Sorted in C-style order:0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50,
YouTip