如何使用x和y坐标遍历2D numpy数组而不会出现越界错误? [英] How to loop through 2D numpy array using x and y coordinates without getting out of bounds error?

查看:74
本文介绍了如何使用x和y坐标遍历2D 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]

这只会打印1-6.

我还尝试仅从范围内的行或列中减去1,但这会导致超出范围的错误或并非所有数字都已打印.

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.

推荐答案

a.shape[0]是行数和第一维的大小,而a.shape[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]

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

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

必须这样,因为数组可以是矩形的(即行!= cols). a.shape是每个维度的大小,以它们的索引顺序为准.因此,如果在编写时shape(10, 5):

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]

x的最大值为9,y的最大值为4. xy实际上是数组索引的较差名称,因为它们不代表数学笛卡尔坐标系,而是代表内存中的位置.您可以改用i和j:

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.

这篇关于如何使用x和y坐标遍历2D numpy数组而不会出现越界错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆