NUMPY Tutorial



NumPy ARRAY ITERATING


🔹 NumPy Array Iterating

Iterating over NumPy arrays allows you to access and manipulate each element efficiently. Unlike Python lists, iterating over NumPy arrays can be done in several ways depending on the array's dimensions and desired operations.

✅ Iterating over 1D Arrays

For 1D arrays, you can use a simple for loop like with Python lists.

import numpy as np

arr = np.array([10, 20, 30, 40])

for element in arr:
    print(element)
# Output:
# 10
# 20
# 30
# 40

✅ Iterating over 2D Arrays

When iterating over 2D arrays, each iteration gives you a 1D array (a row):

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

for row in arr2d:
    print(row)
# Output:
# [1 2 3]
# [4 5 6]
# [7 8 9]

✅ Iterating over Each Element in 2D Arrays

To access every element in a multi-dimensional array, you can use nested loops:

for row in arr2d:
    for elem in row:
        print(elem, end=' ')
    print()
# Output:
# 1 2 3 
# 4 5 6 
# 7 8 9 

✅ Using np.nditer for Efficient Iteration

np.nditer is a powerful iterator object that allows efficient and flexible iteration over arrays of any shape.

for x in np.nditer(arr2d):
    print(x, end=' ')
# Output: 1 2 3 4 5 6 7 8 9

✅ Modifying Array Elements Using np.nditer

You can modify elements during iteration by setting op_flags=['readwrite']:

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

for x in np.nditer(arr_mod, op_flags=['readwrite']):
    x[...] = x * 2

print(arr_mod)
# Output: [ 2  4  6  8]

✅ Iterating with Different Data Types

You can cast types during iteration using flags=['buffered'] and specifying dtype:

arr_float = np.array([1.1, 2.2, 3.3])

for x in np.nditer(arr_float, flags=['buffered'], dtype='int'):
    print(x, end=' ')
# Output: 1 2 3

✅ Iterating Over Multiple Arrays Simultaneously

Using np.nditer with multiple operands lets you iterate over several arrays at once:

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

for x, y in np.nditer([arr1, arr2]):
    print(f"x: {x}, y: {y}")
# Output:
# x: 1, y: 4
# x: 2, y: 5
# x: 3, y: 6

Summary:

  • Simple for loops work well for 1D and row-wise 2D array iteration.
  • Nested loops access every element in multi-dimensional arrays.
  • np.nditer is a flexible, memory-efficient way to iterate over arrays.
  • You can modify array elements and iterate over multiple arrays simultaneously with np.nditer.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review