Python - Iterating NumPy Arrays

Example : for loop
x = np.array([[-1, 1], [-2, 2]])
for row in x:
    print('Row :',row)
Output
Row : [-1  1]
Row : [-2  2]

Example : nditer
import numpy as np
x = np.array([[0,1], [2, 3]])
for a in np.nditer(x):
    print(a)
Output
0
1
2
3
Example : Boolean
import numpy as np
x = np.arange(10).reshape(2,5)
condition = x % 2 == 0
print(condition)
print(x[condition])
Output
[[ True False  True False  True]
 [False  True False  True False]]
[0 2 4 6 8]



No comments:

Post a Comment