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:

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

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:

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:

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

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:

Reshape a Numpy array
Joining Numpy Arrays
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment