Categories: R Programming

How to iterate over an Numpy array in Python

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.

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago