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.
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
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]
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
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
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]
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
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
for
loops work well for 1D and row-wise 2D array iteration.np.nditer
is a flexible, memory-efficient way to iterate over arrays.np.nditer
.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!