Select to view content in your preferred language

Not sure how to fix an Index Error

5643
11
09-30-2015 10:59 AM
RachelAlbritton
Frequent Contributor

I am working on updating a python script that was created in python 2.6 for ArcGIS 10.0.

We are now working with python 2.7.8 in ArcGIS 10.3

I did not write the script and am still a little fuzzy on exactly what its doing (which is probably why I need help figuring out this error).

The script is performing a Moore Neighborhood analysis on an array where it's walking through each cell in the DEM raster and comparing that cell value to the 8 surrounding cells, it extracts a minimum value from those 8 cells and then inserts that value into a corresponding constant array.

The script runs through the first 3 if statements ok, but then gets to the 4th one and throws the error:

Traceback (most recent call last):

  File "S:\Rachel\Projects\Storm_Sewer\Python\Surface_Flow.py", line 51, in <module>

    if myArray>myArray[u-1][v+1]:

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

Presumably, the script is calculating something outside a a predefined range but I'm not sure what that is and/or how to fix it so that the script still returns the correct values.

Both the original DEM and constant raster's were floating values before turning them into arrays. Not sure if that's relevant.

SCRIPT:

#Global Variables:
t=numpy.empty((49,1))
c=0

#Turn DEM into an array matrix.
myArray = arcpy.RasterToNumPyArray(DEM)
constant2 = arcpy.RasterToNumPyArray(constant)

#Moore Neighborhood Analysis
#Neighboorhood Analysis  will walk through each cell comparing all surrounding
#cells, extract minimum values, and insert them into the constant raster location

for u in range(len(myArray)-1):
    for v in range(len(myArray)-1):
        
        if myArray>myArray[u-1]:
            constant2[u-1]=myArray[u-1]

        if myArray>myArray[u+1]:
            constant2[u+1]=myArray[u+1]

        if myArray>myArray[u-1][v-1]:
            constant2[u-1][v-1]=myArray[u-1][v-1]

        if myArray>myArray[u-1][v+1]:
            constant2[u-1][v+1]=myArray[u-1][v+1]

        if myArray[u+1][v+1]>myArray[u+1][v+1]:
            constant2 [u+1][v+1]=myArray[u+1][v+1]

        if myArray>myArray[u+1][v-1]:
            constant2 [u+1][v-1]=myArray[u+1][v-1]

        if myArray>myArray[v+1]:
            constant2[v+1]=myArray[v+1]

        if myArray[v-1]>myArray[v-1]:
            constant2[v-1]=myArray[v-1]
0 Kudos
11 Replies
DerekNalder
Occasional Contributor

There is a problem with your for loops. When you use RasterToNumPyArray you create a multidimensional array into your myArray variable. I would try adding "" to the second for loop statement as seen below

for u in range(len(myArray)-1):
    for v in range(len(myArray)-1):
RachelAlbritton
Frequent Contributor

So the script ran, but all the cells were returned as no data.

0 Kudos