29 Mar How to Iterate Numpy Arrays
Iteration displays each element of an array. Here, we will see how to iterate through Numpy arrays using loops and other methods. We will cover the following examples:
- Iterate a One-Dimensional Numpy array
- Iterate a Two-Dimensional Numpy array
- Iterate over a Three-Dimensional Numpy array
Printing vs Iterating
- print(n) → shows the whole array structure in NumPy’s representation. This prints the entire NumPy array in one go. The NumPy array will get displayed in a compact format, with elements separated by spaces (not commas like Python lists).
- Iteration with a for loop, i.e., (for a in n: print(a)) → shows the individual elements one by one, each on its own line. This loop iterates through the array and prints each element individually.
Iterate a One-Dimensional Numpy array
Let us see how to iterate a one-dimensional array using for loop in Numpy:
# Iterate a One-Dimensional Array in NumPy
import numpy as np
# Create a 1D array
n = np.array([15, 29, 30, 45, 55, 69, 72, 88, 90])
# shows the whole array structure in NumPy’s representation
print(n)
# shows the individual elements one by one, each on its own line
for a in n:
print(a)
Output
[15 29 30 45 55 69 72 88 90] 15 29 30 45 55 69 72 88 90
Iterate a Two-Dimensional Numpy array
Let us see how to iterate a two-dimensional array using for loop in Numpy:
import numpy as np
# Create a Numpy 2D array
n = np.array([[5, 10], [15, 20], [25, 30]])
print("Two-Dimensional Array = \n", n)
print("Type = ", type(n))
print("DataType = ", n.dtype)
print("\nIterating...")
for a in n:
print(a)
Output
Two-Dimensional Array = [[ 5 10] [15 20] [25 30]] Type = <class 'numpy.ndarray'> DataType = int32 Iterating... [ 5 10] [15 20] [25 30]
Iterate a Three-Dimensional Numpy array
Let us see how to iterate a three-dimensional array using for loop in Numpy. The 2D matrices are iterated one by one for 3D array iteration. Let us see an example:
# Iterate a Three-Dimensional Array in NumPy
import numpy as np
# Create a 3D array
n = np.array([
[[5, 10],
[20, 30]],
[[45, 80],
[90, 130]],
[[55, 98],
[290, 340]]
])
print(n)
print(n.ndim)
print(n.shape)
for a in n:
print("Each matrix:\n",a)
Output
[[[ 5 10] [ 20 30]] [[ 45 80] [ 90 130]] [[ 55 98] [290 340]]] 3 (3, 2, 2) Each matrix: [[ 5 10] [20 30]] Each matrix: [[ 45 80] [ 90 130]] Each matrix: [[ 55 98] [290 340]]
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments