Numpy Accessing Array Elements Iteration

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will learn how to use the numpy.nditer object to iterate over a NumPy array and access its individual elements. We will also learn how to modify the elements of an array using the op_flags parameter of the nditer object. Lastly, we will learn about broadcasting in NumPy arrays using the nditer object.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Create an ndarray and iterate over it using numpy.nditer

In this step, we will create a one-dimensional NumPy array using the arange() method, and then iterate over it using the numpy.nditer object.

import numpy as np

a = np.arange(0,40,5)

print ("The Original array is:")
print (a)
print ('\n')

## showing elements of array one by one
print ("The Modified array is:")
for x in np.nditer(a):
    print(x)

Iterate over the transpose of an array

In this step, we will take a two-dimensional NumPy array, find its transpose, and iterate over it using the nditer object.

import numpy as np

a = np.array([[11,2,3,4],[29,4,15,6],[11,21,39,31]])
print("The array is :")
print(a)

print("The transpose of the array is :")
at = a.T
print(at)

print("Iterating over the array:")
for x in np.nditer(at):
    print(x, end=' ')

Iterate over an array in C-style order and in F-style order

In this step, we will create a two-dimensional NumPy array, find its transpose, and then iterate over it in both C-style and F-style order using the nditer object.

import numpy as np

a = np.array([[1,2,3,4],[8,9,5,6],[10,20,29,31]])
print("\nPrinting the array:\n")
print(a)

print("\nPrinting the transpose of the array:\n")
at = a.T
print(at)

print("\nIterating over the transposed array in F-style order:\n")
for x in np.nditer(at, order='F'):
    print(x, end=' ')

print("\nIterating over the transposed array in C-style order:\n")
for x in np.nditer(at, order='C'):
    print(x, end=' ')

Iterate over multiple arrays using broadcasting

In this step, we will create two NumPy arrays of different dimensions and iterate over them using broadcasting with the nditer object.

import numpy as np

a = np.arange(0,60,5)
a = a.reshape(3,4)

print ('The First array :')
print (a)
print ('\n')

print ('The Second array is')
b = np.array([1, 2, 3, 4], dtype = int)
print (b)
print ('\n' )

print ('The Modified array is')
for x,y in np.nditer([a,b]):
    print ("%d:%d" %(x,y))

Modify the values of an array using op_flags

In this step, we will create a one-dimensional NumPy array, iterate over it using the nditer object while setting the op_flags parameter to 'readwrite', and then modify the elements of the array as we iterate over them.

import numpy as np

a = np.arange(0,50,6)
a = a.reshape(3,3)

print ('The Original array is:')
print (a)
print ('\n')

for x in np.nditer(a, op_flags=['readwrite']):
    x[...] = 2 + x

print ('The Modified array is:')
print (a)

Summary

In this lab, we learned how to use the nditer object in NumPy to iterate over arrays, and how to modify the elements of an array during iteration using the op_flags parameter. We also learned about broadcasting in NumPy arrays using the nditer object to iterate over multiple arrays concurrently.

Other Python Tutorials you may like