如何使用x和y坐标循环2D numpy数组而不会超出界限错误?

Com*_*PVT 15 python arrays numpy

我尝试过以下方法:

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]
Run Code Online (Sandbox Code Playgroud)

这将只打印数字1 - 6.

我也尝试过从范围中的行或列中减去1,但这会导致越界错误或者不会打印所有数字.

Mar*_*hke 35

你得到更漂亮的代码:

for ix,iy in np.ndindex(a.shape):
    print(a[ix,iy])
Run Code Online (Sandbox Code Playgroud)

导致:

1
2
3
4
5
6
7
8
9
10
11
12
Run Code Online (Sandbox Code Playgroud)


fou*_*nes 11

a.shape[0]是第一个维度的行数和大小,而a.shape[1]第二个维度的大小.你需要写:

for x in range(0, rows):
    for y in range(0, cols):
        print a[x,y]
Run Code Online (Sandbox Code Playgroud)

请注意range()函数中如何交换行和列.

编辑:必须这样,因为数组可以是矩形(即行!= cols).a.shape是每个维度的大小,按索引的顺序排列.因此,如果shape(10, 5)当你写:

a[x, y]
Run Code Online (Sandbox Code Playgroud)

x的最大值为9,y的最大值为4. x并且y实际上是数组索引的名称不佳,因为它们不代表数学cartesisan坐标系,而是表示内存中的位置.您可以使用i和j代替:

for i in range(0, rows):
    for j in range(0, cols):
        print a[i,j]
Run Code Online (Sandbox Code Playgroud)

文档是有点长,但具有指标和形状的一个很好的深入描述.