If we want to get the contents of an Numpy array element by element, a for loop can be performed. The usage of a for loop upon an Numpy array is quite similar as for a Python list, which is show in the following code example.
#import Numpy module
import numpy as np
#create an one-dimensional array
b = np.array([9, 2.5, 3.6, 12, 69, 72])
b
#Output
array([ 9. , 2.5, 3.6, 12. , 69. , 72. ])
#using for loop printing out every element of the array
for eb in b:
print(eb)
For two-dimensional array, for loop will first looping over the row, which is the first axis, then over each element inside each row.
#create a two-dimensional array
B2 = np.arange(1, 9).reshape((4, 2))
B2
#output
array([[1, 2],
[3, 4],
[5, 6],
[7, 8]])
#looping over row by row, then element by element from each row
for s in B2:
for s1 in s:
print(s1)
#output
1
2
3
4
5
6
7
8
For getting out all the contents of a higher-dimensional Numpy array, an alternative way is using flat method over the array.
#flat method to get out each element
for item in B2.flat:
print(item)
#result
1
2
3
4
5
6
7
8
0 Comments