简体   繁体   中英

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

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.

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

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 (ie 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.

You can use xrange .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM