NumPy - ndarray.flat function
The NumPy ndarray.flat() is an array attribute and it is a 1-D iterator over the array.
Syntax
numpy.ndarray.flat
Parameters
No parameter is required.
Return Value
Returns a 1-D iterator over the array.
Example:
In the example below, ndarray.flat is used to access elements of an array.
import numpy as np x = np.array([[10,20,30], [40,50,60]]) n = x.size #displaying all elements using flat attribute y1 = x.flat[0:n] print("x.flat[0:n] =", y1) #displaying 3rd element using flat attribute y2 = x.flat[3] print("x.flat[3] =", y2) print() #displaying all elements using flat attribute #on transpose of the array y3 = x.T.flat[0:n] print("x.T.flat[0:n] =", y3) #displaying 3rd element using flat attribute #on transpose of the array y4 = x.T.flat[3] print("x.flat[3] =", y4)
The output of the above code will be:
x.flat[0:n] = [10 20 30 40 50 60] x.flat[3] = 40 x.T.flat[0:n] = [10 40 20 50 30 60] x.flat[3] = 50
Example:
The ndarray.flat attribute can be used to assign value to the array.
import numpy as np x = np.array([[10,20,30], [40,50,60]]) y = np.array([[10,20,30], [40,50,60]]) #assign value to all elements #of the array using flat attribute x.flat = 10 print("x =") print(x) print() #assign value to given elements #of the array using flat attribute y.flat[[1, 2, 3]] = 5 print("y =") print(y)
The output of the above code will be:
x = [[10 10 10] [10 10 10]] y = [[10 5 5] [ 5 50 60]]
❮ NumPy - Functions