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

Question:

I have tried the following:

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
print a
rows = a.shape[0]
cols = a.shape[1]
print rows
print cols

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

This will only print numbers 1 – 6.

I have also tried only subtracting 1 from either rows or cols in the range, but that either leads to out of bounds error or not all numbers printed.

Asked By: CompSci-PVT

||

Answers:

You can use xrange.

for x in xrange(rows):
    for y in xrange(cols):
        print a[x,y]
Answered By: Avión

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.

Answered By: fouronnes

You get prettier code with:

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

resulting in:

1
2
3
4
5
6
7
8
9
10
11
12
Answered By: Markus Dutschke

You can use np.nditer.

it = np.nditer(a, flags=['multi_index'])
for x in it:
    print("{} {}".format(x, it.multi_index))

Reference: Iterating Over Arrays

Answered By: LunaElf
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.