Thursday, May 28, 2020

Iterating Over Arrays

Iterating Over Arrays


The most popular and well-known way iterate over an ndarray is a basic iteration loop available in Python.
 
For example,

import numpy as np
# Accessing using for loop
#1-D array
lang = np.array(['Java','Python','C++','C#','C','JavaScript']);
for item in lang:
  print(item)


#2-D array
nums = np.array([[10, 20, 30],[40, 50, 60],[70, 80, 90]])
for row in nums:
  for item in row:
    print(item)
    
#3-D array
nums3d = np.array([[[10, 20, 30],[40, 50, 60]],[[70, 80, 90],[100, 110, 120]]])
for row in nums3d:
  for col in row:
    for item in col:
      print(item)


Iterating over nditer()


NumPy package also provides an iterator object numpy.nditer(). We can use this efficient multidimensional iterator object to iterate over an array. Each item of the array can be accessed using numpy.nditer(). We can perform from very basic to advanced iterations using this function.

for example,

import numpy as np
#1-D array
lang = np.array(['Java','Python','C++','C#','C','JavaScript']);
for item in np.nditer(lang):
  print(item)
  
#2-D array
nums = np.array([[10, 20, 30],[40, 50, 60],[70, 80, 90]])
for item in np.nditer(nums):
    print(item)
    
#3-D array
nums3d = np.array([[[10, 20, 30],[40, 50, 60]],[[70, 80, 90],[100, 110, 120]]])
for item in np.nditer(nums3d):
      print(item)


Iterating Array with different dtype


You can choose op_dtypes parameter and pass it the expected ndarray dtype to change the datatype of the items during iteration. Item’s Actual datatype is not changed, so it will require additional memory space to perform this task. This additional space is known as a buffer and in order to enable it in numpy.nditer() we need to pass flags=['buffered'].

import numpy as np

nums = np.array([100, 200, 300])

for item in np.nditer(nums, flags=['buffered'], op_dtypes=['S']):
  print(item)

#Output
b'100'
b'200'
b'300'

Modifying the step size for iteration


You can apply filtering, followed by iteration.

import numpy as np
nums = np.array([[10, 20, 30, 40, 50], [60, 70, 80, 90, 100]])
#skip one item
for item in np.nditer(nums[:, ::2]):
  print(item)
  
#Output
10
30
50
60
80
100

Enumerated iteration with nditer()


Sometimes we need to work with the index of the item in an array. For such cases, we can use ndenumerate() method.

For example

import numpy as np
#1-D array
lang = np.array(['Java','Python','C++','C#','C','JavaScript']);
for i,item in np.ndenumerate(lang):
  print(i,item)

#Output
(0,) Java
(1,) Python
(2,) C++
(3,) C#
(4,) C
(5,) JavaScript
Similarly, we can enumerate 2-D or 3-D arrays,

import numpy as np
#2-D array
nums = np.array([[10, 20, 30],[40, 50, 60],[70, 80, 90]])
for i, item in np.ndenumerate(nums):
    print(i, item)


#Output
(0, 0) 10
(0, 1) 20
(0, 2) 30
(1, 0) 40
(1, 1) 50
(1, 2) 60
(2, 0) 70
(2, 1) 80
(2, 2) 90