Iterating NumPy Array Using For Loop

Author: Al-mamun Sarkar Date: 2020-03-31 17:50:33

Iterating NumPy Array Using For Loop. The following shows the various ways for iterating the NumPy array of Python NumPy module. 

 

import numpy as np

 

Code:

a = np.arange(10)**3
a

Output:

array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])

 

Code:

for i in a:
    print(i**(1/3.))

Output: 

nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0

 

Code:

def f(x,y):
    return 10*x+y

b = np.fromfunction(f,(5,4),dtype=int)
b

Output:

array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])

 

Code:

for row in b:
    print(row)

 Output:

[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]

 

Code:

for element in b.flat:
    print(element)

 Output:

0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43