HOW TO ITERATE NUMPY ARRAYS?

We can iterate on the elements of NumPy Arrays by using for loops.

Iterating 1-D Array-

import numpy as np

arr = np.array([1, 2, 3])

for x in arr:
  print(x)

Output-

1
2
3

Iterating 2-D Arrays

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

for x in arr:
  print(x)

Output-

[1 2 3]
[4 5 6]

Iterating on each element of the 2-D array

import numpy as np

arr1 = np.array([[1, 2, 3], [4, 5, 6]])

for x in arr1:
  for y in x:
    print(y)

Output-

1
2
3
4
5
6

Iterating 3-D Arrays-

import numpy as np

arr1 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

for x in arr1:
  print(x)

Output

[[1 2 3]
 [4 5 6]]
[[ 7  8  9]
 [10 11 12]]

To iterate on each scalar value of 3D array, we need to iterate in each dimension-

import numpy as np

arr1 = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

for x in arr1:
  for y in x:
    for z in y:
      print(z)

Output-

1
2
3
4
5
6
7
8
9
10
11
12

Iterating Arrays Using nditer()

nditer() method is capable of iterating on each scalar element of the array.

import numpy as np

arr1 = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

for x in np.nditer(arr1):
  print(x)

Output-

1
2
3
4
5
6
7
8

Iterating Array With Different Data Types-

To change the datatype of elements while iterating we can use op_dtypes argument with expected data type in nditer() method as shown in following example-

import numpy as np

arr1 = np.array([1, 2, 3])

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

Output-

b'1'
b'2'
b'3

Iterating With Different Step Size-

Step is used to skip the element by specified no. while iterating the elements of array

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

for x in np.nditer(arr[:, ::2]):
  print(x)

Output-

1
3
5
7

Enumerated Iteration Using ndenumerate()

Mentioning sequence no. of something while iterating on each element is known as enumerated iteration.

Theย ndenumerate()ย method can be used for getting corresponding index of the element while iterating,ย 

import numpy as np

arr1 = np.array([1, 2, 3])

for idx, x in np.ndenumerate(arr1):
  print(idx, x)

Output-

(0,) 1
(1,) 2
(2,) 3

Enumerate on following 2D array’s elements-

import numpy as np

arr2D = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

for idx, x in np.ndenumerate(arr2D):
  print(idx, x)

Output-

(0, 0) 1
(0, 1) 2
(0, 2) 3
(0, 3) 4
(1, 0) 5
(1, 1) 6
(1, 2) 7
(1, 3) 8

Posted

in

Tags:

Comments

Leave a Reply