Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Iterating 3-D Arrays

In a 3-D array, it will iterate through all the 2-D arrays.

Example

Iterate through the elements of the following 3-D array:

import numpy as np

arr = np.array([[[123], [456]], [[789], [101112]]])

for x in arr:
  print(x)

To retrieve the actual values, or scalars, we need to iterate through the arrays in each dimension.

Example

Iterate down to the scalar values:

import numpy as np

arr = np.array([[[123], [456]], [[789], [101112]]])

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

Iterating Arrays Using nditer()

The nditer() function is a utility that can be utilized for both basic and advanced iterations. It addresses some common challenges encountered during iteration; let’s explore it through examples.

Iterating on Each Scalar Element

In basic for loops, iterating through each scalar of an array requires using multiple nested loops (n loops), which can be challenging to write for arrays with high dimensionality.

Example

Iterate through the elements of the following 3-D array:

import numpy as np

arr = np.array([[[12], [34]], [[56], [78]]])

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

Iterating Array With Different Data Types

We can utilize the op_dtypes argument and specify the expected data type to change the data type of elements during iteration.

 

NumPy does not modify the element’s data type in place (within the original array); instead, it requires additional space to perform this action. This extra space is referred to as a buffer, and to enable it in nditer(), we pass flags=[‘buffered’].

Example

Iterate through the array as if it were a string:

import numpy as np

arr = np.array([123])

for x in np.nditer(arr, flags=[‘buffered’], op_dtypes=[‘S’]):
  print(x)