We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental level, click here for more details.

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

You can also watch videos on our YouTube channel for more understanding of Python programming skills.

Categories: R Programming

0 Comments

Leave a Reply

Avatar placeholder