Iterating Over a NumPy Array
This post explains how to iterate over each element of the NumPy array. We iterate the array by cycling through every element individually. You can install NumPy in your terminal window by running the following command.
pip install numpy
Each script should then have the following code added at the top. This code snippet will allow us to use the NumPy library.
import numpy
NumPy is now ready to use. Let’s see the following example to understand NumPy better.
Example:
import numpy as np array_given = np.array([1, 2, 3, 4, 5]) print(array_given)
Output:
[1 2 3 4 5]
In NumPy, we deal with multi-dimensional arrays, but how? By using for
loop in Python. Whenever we iterate a 1-Dimensional array, each element will be processed individually.
Iterating over a 1-D array
import numpy as np
array = np.array([3, 4, 5])
for iteration in array:
print(iteration)
Output:
1
2
3
Iterating over a 2-D array
Multidimensional arrays have more than one dimension. Multidimensional arrays are just collections of arrays with lower dimensions. One-dimensional arrays only contain elements, while multidimensional arrays contain smaller arrays.
- First, iterate over the smaller dimension array, then over the 1-D array present.
- Performing this operation for the multidimensional array will iterate over all array elements.
If the array is two-dimensional, it will pass through all rows.
import numpy as np
array = np.array([[1, 2, 3], [4, 5, 6]])
for iteration in array:
print(iteration)
Output:
[1 2 3]
[4 5 6]
Iterating over a 3-D array
How about iterating over a 3-Dimensional array? Three-dimensional arrays are collections of two-dimensional arrays. There are three subscripts for this: Block size, row size, and column size. An array with more dimensions can store more data.
import numpy as np
array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
for iteration in array:
print(iteration)
Output:
[[1 2]
[3 4]]
[[5 6]
[7 8]]
Now, what to do when we want to iterate down to the scalers? Do this, by using nested for loops.
The term nested loop refers to loops that are nested within each other. In other words, enclosing a while loop within a for loop, or enclosing a for loop within a for loop, for loop inside a for loop, and so on.
import numpy as np
array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
for iteration_1 in array:
for iteration_2 in iteration_1:
for iteration_3 in iteration_2:
print(iteration_3)
Output:
1
2
3
4
5
6
7
8
With these examples, we have concluded our tutorial on how to Iterate over a NumPy array.
Do you want to learn how to shuffle NumPy arrays in Python? Follow this post How to shuffle NumPy Array in Python?
Leave a Reply