Numpy | Iterating Over Array

Last Updated : 25 Jan, 2024

NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface.


# Python program for
# iterating over array

import numpy as geek

# creating an array using arrange 
# method
a = geek.arange(12)

# shape array with 3 rows and 
# 4 columns
a = a.reshape(3,4)

print('Original array is:')
print(a)
print()

print('Modified array is:')

# iterating  an array
for x in geek.nditer(a):
    print(x)

Output:

Original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Modified array is:
0 1 2 3 4 5 6 7 8 9 10 11

The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array.


# Python program for
# iterating over transpose
# array

import numpy as geek 

# creating an array using arrange 
# method
a = geek.arange(12)

# shape array with 3 rows and 
# 4 columns 
a = a.reshape(3,4) 
   
print('Original array is:')
print(a)
print()  
   
# Transpose of original array
b = a.T 
   
print('Modified array is:')
for x in geek.nditer(b): 
    print(x)


Output:

Original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Modified array is:
0 1 2 3 4 5 6 7 8 9 10 11

 

Controlling Iteration Order:
There are times when it is important to visit the elements of an array in a specific order, irrespective of the layout of the elements in memory. The nditer object provides an order parameter to control this aspect of iteration. The default, having the behavior described above, is order=’K’ to keep the existing order. This can be overridden with order=’C’ for C order and order=’F’ for Fortran order.

Code #1:


# Python program for
# iterating over array
# using particular order

import numpy as geek 

# creating an array using arrange 
# method
a = geek.arange(12) 

# shape array with 3 rows and 
# 4 columns 
a = a.reshape(3,4) 

print('Original array is:') 
print(a)
print()  

print('Modified array in C-style order:')

# iterating an array in a given
# order  
for x in geek.nditer(a, order = 'C'): 
    print(x)

Output:

Original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Modified array in C-style order:
0 1 2 3 4 5 6 7 8 9 10 11

 
Code #2:


# Python program for
# iterating over array
# using particular order

import numpy as geek 

# creating an array using arrange 
# method
a = geek.arange(0,60,5) 

# shape array with 3 rows and 
# 4 columns 
a = a.reshape(3,4) 

print('Original array is:') 
print(a)
print()  

print('Modified array in F-style order:')

# iterating an array in a given
# order   
for x in geek.nditer(a, order = 'F'): 
    print(x)

Output:

Original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Modified array in F-style order:
0 4 8 1 5 9 2 6 10 3 7 11

 

Modifying Array Values:
The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator.


# Python program for
# modifying array values

import numpy as geek

# creating an array using arrange 
# method
a = geek.arange(12)

# shape array with 3 rows and 
# 4 columns 
a = a.reshape(3,4)
print('Original array is:')
print(a)
print()

# modifying array values
for x in geek.nditer(a, op_flags = ['readwrite']):
    x[...] = 5*x
print('Modified array is:')
print(a)

Output:

Original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Modified array is:
[[ 0 5 10 15]
 [20 25 30 35]
 [40 45 50 55]]

 

External Loop:

The nditer class constructor has a flags parameter, which can take the following values

Parameter Description
external_loop Causes values given to be one-dimensional arrays with multiple values instead of zero-dimensional array
c_index C_order index can be tracked
f_index Fortran_order index is tracked
multi-index Type of indexes with one per iteration can be tracked

Code #1:


# Python program for
# iterating array values
# using external loop

import numpy as geek 

# creating an array using arrange 
# method
a = geek.arange(12) 

# shape array with 3 rows and 
# 4 columns 
a = a.reshape(3,4) 

print('Original array is:') 
print(a) 
print()  

print('Modified array is:') 
for x in geek.nditer(a, flags = ['external_loop'], order = 'C'):
    print(x)

Output:

Original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Modified array is:
[ 0 1 2 3] [ 4 5 6 7] [8 9 10 11] 

 

Code #2:


# Python program for
# iterating array values
# using f_index

import numpy as geek 

# creating an array using arrange 
# method
a = geek.arange(6)

# shape array with 2 rows and 
# 3 columns 
a = a.reshape(2,3)

print('Original array is:')
print(a)
print()

# iterating array using f_index 
# parameter
it = geek.nditer(a, flags=['f_index'])
while not it.finished:
      print("%d <%d>" % (it[0], it.index), end=" ")
      it.iternext()

Output:

Original array is:
[[ 0 1 2]
 [ 3 4 5]]

0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5>

 

Broadcasting Iteration:
If two arrays are broadcastable, a combined nditer object is able to iterate upon them concurrently. Assuming that an array a has dimension 3X4, and there is another array b of dimension 1X4, the iterator of following type is used (array b is broadcast to size of a).


# Python program for
# iterating array 

import numpy as geek

# creating an array using arrange 
# method 
a = geek.arange(12)

 # shape array with 3 rows and 
# 4 columns 
a = a.reshape(3,4) 

print('First array is:') 
print(a)
print()  

# Creating second array using 
# array method
print('Second array is:') 
b = geek.array([5, 6, 7, 8], dtype = int) 
print(b)  
print() 

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

Output:

First array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Second array is:
[5 6 7 8]

Modified array is:
0:5 1:6 2:7 3:8 4:5 5:6 6:7 7:8 8:5 9:6 10:7 11:8

 


Share your thoughts in the comments

Similar Reads