NumPy provides an iterator object, i.e., nditer which can be used to iterate over the given array using python standard Iterator interface.
Consider the following example.
import numpy as np a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]]) print("Printing array:") print(a); print("Iterating over the array:") for x in np.nditer(a): print(x,end=' ')
Output:
Order of the iteration doesn't follow any special ordering like row-major or column-order. However, it is intended to match the memory layout of the array.
Let's iterate over the transpose of the array given in the above example.
import numpy as np a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]]) print("Printing the array:") print(a) print("Printing the transpose of the array:") at = a.T print(at) #this will be same as previous for x in np.nditer(at): print(print("Iterating over the array:") for x in np.nditer(a): print(x,end=' ')
Output:
As we know, there are two ways of storing values into the numpy arrays:
Let's see an example of how the numpy Iterator treats the specific orders (F or C).
import numpy as np a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]]) print("\nPrinting the array:\n") print(a) print("\nPrinting the transpose of the array:\n") at = a.T print(at) print("\nIterating over the transposed array\n") for x in np.nditer(at): print(x, end= ' ') print("\nSorting the transposed array in C-style:\n") c = at.copy(order = 'C') print(c) print("\nIterating over the C-style array:\n") for x in np.nditer(c): print(x,end=' ') d = at.copy(order = 'F') print(d) print("Iterating over the F-style array:\n") for x in np.nditer(d): print(x,end=' ')
Output:
We can mention the order 'C' or 'F' while defining the Iterator object itself. Consider the following example.
import numpy as np a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]]) print("\nPrinting the array:\n") print(a) print("\nPrinting the transpose of the array:\n") at = a.T print(at) print("\nIterating over the transposed array\n") for x in np.nditer(at): print(x, end= ' ') print("\nSorting the transposed array in C-style:\n") print("\nIterating over the C-style array:\n") for x in np.nditer(at, order = 'C'): print(x,end=' ')
Output:
We can not modify the array elements during the iteration since the op-flag associated with the Iterator object is set to readonly.
However, we can set this flag to readwrite or write only to modify the array values. Consider the following example.
import numpy as np a = np.array([[1,2,3,4],[2,4,5,6],[10,20,39,3]]) print("\nPrinting the original array:\n") print(a) print("\nIterating over the modified array\n") for x in np.nditer(a, op_flags = ['readwrite']): x[...] = 3 * x; print(x,end = ' ')
Output: