Iterating over an numpy array#

To iterate over the rows of a 2d numpy array we use:

import numpy as np #Run this cell or none of the np commands will work
two_dim_array = np.array([[1.4, 2.3, 5.3],[1.5, 3.2, 6.7]])

for row in two_dim_array:
    print("######################")
    print(f"the row is {row}")
######################
the row is [1.4 2.3 5.3]
######################
the row is [1.5 3.2 6.7]

Exercise 4.1#

Please evaluate the cell below.

two_dim_array_rand =  np.random.uniform(0, 100, size = (5, 10))

In the cell below iterate over each row of the above 2d numpy array, and print the (elementwise) square root of each row.

To iterate all elements of the array we can use the flat function:

for element in two_dim_array.flat:
    print("######################")
    print(f"the element is {element}")
######################
the element is 1.4
######################
the element is 2.3
######################
the element is 5.3
######################
the element is 1.5
######################
the element is 3.2
######################
the element is 6.7

but perhaps it is easier to understand this if we loop over the rows and then loop over the columns within this loop (so using nested looping as we introduced in the third week!)

for row in two_dim_array:
    for element in row:
        print("######################")
        print(f"the element is {element}")
######################
the element is 1.4
######################
the element is 2.3
######################
the element is 5.3
######################
the element is 1.5
######################
the element is 3.2
######################
the element is 6.7

Exercise 4.2#

Please evaluate the cell below:

three_dim_array =  np.random.uniform(0, 10, size = (5, 4, 2))

In the cell below iterate over each element of the array, and print the square of each element. (Note, that in this three dimensional array you would need three for loops if using nested loops. Using flat would certainly be easier here, but perhaps not so clear)