close

[Solved] How to loop through 2D numpy array using x and y coordinates without getting out of bounds ?

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error How to loop through 2D numpy array using x and y coordinates without getting out of bounds ? in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How to loop through 2D numpy array using x and y coordinates without getting out of bounds Error Occurs?

Today I get the following error How to loop through 2D numpy array using x and y coordinates without getting out of bounds ? in python.

How To Solve loop through 2D numpy array using x and y coordinates without getting out of bounds Error ?

  1. How To Solve loop through 2D numpy array using x and y coordinates without getting out of bounds Error ?

    To Solve loop through 2D numpy array using x and y coordinates without getting out of bounds Error Note how rows and cols have been swapped in the range() function.

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

    To Solve loop through 2D numpy array using x and y coordinates without getting out of bounds Error Note how rows and cols have been swapped in the range() function.

Solution 1

a.shape[0] is the number of rows and the size of the first dimension, while a.shape[1] is the size of the second dimension. You need to write:

for x in range(0, rows):
    for y in range(0, cols):
        print a[x,y]

Note how rows and cols have been swapped in the range() function.

Edit: It has to be that way because an array can be rectangular (i.e. rows != cols). a.shape is the size of each dimension in the order they are indexed. Therefore if shape is (10, 5) when you write:

a[x, y]

the maximum of x is 9 and the maximum for y is 4. x and y are actually poor names for array indices, because they do not represent a mathematical cartesisan coordinate system, but a location in memory. You can use i and j instead:

for i in range(0, rows):
    for j in range(0, cols):
        print a[i,j]

The documentation is a bit long but has a good in-depth description of indices and shapes.

Solution 2


You get prettier code with:

for ix,iy in np.ndindex(a.shape):
    print(a[ix,iy])

resulting in:

1
2
3
4
5
6
7
8
9
10
11
12

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read