How to iterate over NumPy array?

In this tutorial, you will learn two different ways of iterating Numpy array-

  1. Iterating without using nditer
  2. Iterating using nditer

Iterating Numpy Array without using nditer

for and while loop is used to iterate one-dimensional and two-dimensional array.

Iterating a One-dimensional Array

#Python program to iterate 1-D Numpy array using for loop
import numpy as np
 
x = np.array([21, 15, 99, 42, 78])
for cell in x:
  print(cell, end=' ')

Output of the above program

21 15 99 42 78
#Python program to iterate 1-D Numpy array using while loop
import numpy as np
 
x = np.array([21, 15, 99, 42, 78])
i = 0
while i < x.size:
  print(x[i], end=' ')
  i = i + 1

Output of the above program

21 15 99 42 78

Iterating a Two-dimensional Array

To iterate each row, follow the below example-

#Python program to iterate 2-D array using for loop
import numpy as np
 
x = np.array([[21, 15, 99, 42, 78], [11, 54, 34, 76, 89]])
for row in x:
  print(row)

Output of the above program

[21 15 99 42 78]
[11 54 34 76 89]

In case, you want to iterate each cell then go through the below examples-

#Python program to iterate each cell of 2-D array using for loop
import numpy as np
 
x = np.array([[21, 15, 99, 42, 78], [11, 54, 34, 76, 89]])
for row in x:
  for cell in row:
    print(cell, end=' ')
  print()

Output of the above program

21 15 99 42 78
11 54 34 76 89
#Python program to iterate each cell of 2-D array using while loop
import numpy as np
 
x = np.array([[21, 15, 99, 42, 78], [11, 54, 34, 76, 89]])
i = 0
j = 0
rows, cols = x.shape
while i < rows:
  j = 0
  while j < cols:
    print(x[i][j], end=' ')
    j = j + 1
  print()
  i = i + 1

Output of the above program

21 15 99 42 78
11 54 34 76 89

Iterating Numpy Array using nditer

Numpy package provides an iterator object called numpy.nditer. nditer is a multi-dimensional iterator that enables you to iterate each element of Numpy array.

import numpy as np
 
x = np.array([[21, 15, 99, 42, 78], [11, 54, 34, 76, 89]])
print('Array x:\n', x)
print('Iterating array:')
for cell in np.nditer(x):
  print(cell, end=' ')

Output of the above program

Array x:
 [[21 15 99 42 78]
 [11 54 34 76 89]]
Iterating array:
21 15 99 42 78 11 54 34 76 89

Note: The default order of iteration followed by nditer() is as per the memory layout of an array. This thing is noticable when you transpose an array and then iterate it.

import numpy as np
 
x = np.array([[21, 15, 99, 42, 78], [11, 54, 34, 76, 89]])
print('Array x:\n', x)
y = x.T
print('Transposed array:\n', y)
print('Iterating array:')
for cell in np.nditer(y):
  print(cell, end=' ')

Output of the above program

Array x:
 [[21 15 99 42 78]
 [11 54 34 76 89]]
Transposed array:
 [[21 11]
 [15 54]
 [99 34]
 [42 76]
 [78 89]]
Iterating array:
21 15 99 42 78 11 54 34 76 89

As you can see nditer is traversing elements of transposed array according to their memory allocation not as per their order.

How to control iteration order of Numpy nditer?

It is always preferred to access elements as per its layout instead of its memory layout. The default order of iteration of nditer is order='K'. There are two other order of iteration which you can use-

  1. order='C' for C order in which elements of array are traversed horizontally.
  2. order='F' for Fortran order in which elements of array are traversed vertically.
#Python program to iterate array using C and F order
import numpy as np
 
x = np.array([[21, 15, 99], [11, 54, 34], [42, 78, 89]])
print('Array x:\n', x)

print('Iterating array using C order:')
for cell in np.nditer(x, order='C'):
  print(cell, end=' ')

print('\nIterating array using F order:')
for cell in np.nditer(x, order='F'):
  print(cell, end=' ')

Output of the above program

Array x:
 [[21 15 99]
 [11 54 34]
 [42 78 89]]
Iterating array using C order:
21 15 99 11 54 34 42 78 89
Iterating array using F order:
21 11 42 15 54 78 99 34 89

How to modify array values using Numpy nditer?

By default, nditer considers array elements as readonly which means if you try to modify the value then you will get ValueError.

import numpy as np

x = np.array([1, 2, 3, 4, 5])
for t in np.nditer(x):
  t[...] = t * 3

Output of the above program

ValueError: assignment destination is read-only

To get around this problem, you need to use op_flags attribute of nditer. The default value of op_flags attribute is readonly but you can change it to readwrite or writeonly.

import numpy as np

x = np.array([1, 2, 3, 4, 5])
print('Original array is:\n', x)
for t in np.nditer(x, op_flags=['readwrite']):
  t[...] = t * 3
print('Modified array is:\n', x)

Output of the above program

Original array is:
 [1 2 3 4 5]
Modified array is:
 [ 3  6  9 12 15]

How to iterate two arrays simultaneously?

Two arrays can be iterated simultaneously only when they are broadcastable. For more information on Numpy broadcasting, click here. Suppose, there are two arrays- x and y. x has a dimension 4x3 and y has a dimension 1x3. When both of them are iterated simultaneously, then array y will be broadcasted to array x.

import numpy as np

x = np.arange(1,13)
x = x.reshape(4, 3)
print('Array x:\n', x)
y = np.array([15, 30, 45])
print('Array y:\n', y)
print('Iterating arrays simultaneously:')
for a,b in np.nditer([x, y]):
  print('%d:%d' %(a, b))

Output of the above program

Array x:
 [[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
Array y:
 [15 30 45]
Iterating arrays simultaneously:
1:15
2:30
3:45
4:15
5:30
6:45
7:15
8:30
9:45
10:15
11:30
12:45

Recommended Posts