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 a Three-Dimensional Numpy array
Iterate a One-Dimensional Numpy array
Let us see how to iterate a one-dimensional array using for loop in Numpy:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import numpy as np # Create a Numpy 1D array n = np.array([5, 10, 15, 20, 25, 30]) print("One-Dimensional Array = ",n) print("Type = ",type(n)) print("DataType = ",n.dtype) print("\nIterating...") for a in n: print(a) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
One-Dimensional Array = [ 5 10 15 20 25 30] Type = <class 'numpy.ndarray'> DataType = int32 Iterating... 5 10 15 20 25 30 |
Iterate a Two-Dimensional Numpy array
Let us see how to iterate a two-dimensional array using for loop in Numpy:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import numpy as np # Create a Numpy 3D array n = np.array([[[5, 10], [15, 20]], [[25, 30], [35, 40]]]) print("Three-Dimensional Array = \n",n) print("Dimensions = ",n.ndim) print("Type = ",type(n)) print("DataType = ",n.dtype) print("\nIterating...") for a in n: print("Each matrix (2D)=") print(a) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Three-Dimensional Array = [[[ 5 10] [15 20]] [[25 30] [35 40]]] Dimensions = 3 Type = <class 'numpy.ndarray'> DataType = int32 Iterating... Each matrix (2D)= [[ 5 10] [15 20]] Each matrix (2D)= [[25 30] [35 40]] |
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