[Python Cookbook] Numpy: Iterating Over Arrays
1. Using for-loop
Iterate along row axis:
1 import numpy as np 2 x=np.array([[1,2,3],[4,5,6]]) 3 for i in x: 4 print(x)
Output:
[1 2 3]
[4 5 6]
Iterate by index:
for i in range(len(x)): print(x[i])
Output:
[1 2 3]
[4 5 6]
Iterate by row and index:
for i, row in enumerate(x): print('row', i, 'is', row)
Output:
row 0 is [1 2 3]
row 1 is [4 5 6]
2. Using ndenumerate object
for index, i in np.ndenumerate(x):
print(index,i)
Output:
(0, 0) 1
(0, 1) 2
(0, 2) 3
(1, 0) 4
(1, 1) 5
(1, 2) 6
3. Using nditer object
See: https://docs.scipy.org/doc/numpy-1.15.0/reference/arrays.nditer.html
4. Use zip
to iterate over multiple iterables
1 x2 = x**2 2 print(x2,'\n') 3 for i, j in zip(x, x2): 4 print(i,'+',j,'=',i+j)
Output:
[[ 1 4 9]
[16 25 36]]
[1 2 3] + [1 4 9] = [ 2 6 12]
[4 5 6] + [16 25 36] = [20 30 42]