How to loop through 2D NumPy array using x and y coordinates without getting out of bounds error?

Given a 2D NumPy array, we have to loop through 2D NumPy array using x and y coordinates without getting out of bounds error.
By Pranit Sharma Last updated : December 21, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a 2D numpy array and we need to loop over this numpy array using the x and y coordinates. By x and y coordinates, we mean that we need to loop extract all the columns of first row and so on.

Looping through 2D NumPy array using x and y coordinates

For this purpose, we will loop over the numpy array using numpy.nindex() where we will pass the shape of the array. The syntax of numpy.ndindex() is:

class numpy.ndindex(*shape)

The shape is the size of each array's dimension of the array can be passed as individual parameters or as the elements of a tuple.

Let us understand with the help of an example,

Python code to loop through 2D NumPy array using x and y coordinates without getting out of bounds error

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])

# Display original array
print("Original Array:\n",arr,"\n")

# looping over the array
for iy, ix in np.ndindex(arr.shape):
    print(arr[iy, ix])

Output

Example: How to loop through 2D NumPy array using x and y coordinates without getting out of bounds error?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.