遍历NDimensional数组时的索引器错误

2024-05-08 01:49:01 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题中提到的,在遍历n维数组时,我得到了一个索引器。我试图对代码做的是将矩阵的部分设置为0,并保留其余的数据。你知道吗

我还意识到,在n维数组中选择元素应该是array[row#][column#],但这只是我的命名约定的问题,稍后我会解决这个问题。但是,这些值是正确的。你知道吗

currentMatrix = np.array(ast.literal_eval(safety.iloc[i]), dtype=np.int)
currentMatrix.shape = (27,15)

tpHeight = int(df['touchH'].iloc[i])
tpWidth = int(df['touchW'].iloc[i])

fullRows = np.arange(15)
fullColumns = np.arange(27)

beforeAreaColumns = np.arange(df['touchX'].iloc[i] - 1, dtype=np.int)
afterAreaColumns = np.arange(df['touchX'].iloc[i] + tpWidth - 1, dtype=np.int)

beforeAreaRows = np.arange(df['touchY'].iloc[i] - 1, dtype=np.int)
afterAreaRows = np.arange(df['touchY'].iloc[i] + tpHeight - 1, dtype=np.int)

print beforeAreaColumns #returns [0 1 2 3 4 5] at i = 0

currentMatrix[beforeAreaColumns][fullRows] = 0
currentMatrix[afterAreaColumns][fullRows] = 0
currentMatrix[fullColumns][beforeAreaRows] = 0
currentMatrix[fullColumns][afterAreaRows] = 0

我收到的错误是:

IndexError                                Traceback (most recent call last)
<ipython-input-114-342e7c1b89ae> in <module>()
     26     print beforeAreaColumns
     27     
---> 28     currentMatrix[beforeAreaColumns][fullRows] = 0
     29     currentMatrix[afterAreaColumns][fullRows] = 0
     30     currentMatrix[fullColumns][beforeAreaRows] = 0

IndexError: index 6 is out of bounds for axis 0 with size 6

据我所知,我得到这个错误是因为代码试图在只有6个位置的情况下在位置7中查找索引。但是,我不知道为什么数组在索引5处停止时会尝试索引6。你知道吗

我尝试更改代码以便用于循环,例如:

for beforeAreaColumn in beforeAreaColumns:
    for fullRow in fullRows:
        currentMatrix[beforeAreaColumn][fullRow] = 0

但我也犯了同样的错误。上面的代码是在python2.7上编写和运行的。你知道吗


Tags: 代码df错误np数组intdtypearange