NumPy: Iterating Array with different step size

This method is used for iterating when we want to do iterations of a particular part of the given array. This method can iterate the first,  last elements or every other element present in the array. Python has strong indexing built-in capabilities. Thus, here we can perform slicing with iteration to get the particular part of the array.

Example - 1:

import numpy as np
a=np.array([['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']])
#When we take 3 steps
for x in np.nditer(a[:,::3]):
    print(x)

Output:

a
d
g
j

Example - 2:

import numpy as np
a=np.array([['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']])
#When we take 2 steps
for y in np.nditer(a[:,::2]):
    print(y)

Output:

a
c
d
f
g
i
j
l
Thu, 09/09/2021 - 21:56

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.