1

I have a fishnet grid (polygon SHP), and all the little fishnets have a "Zone_ID." There are generally several dozen to a few hundred fishnet polys associated with each Zone_ID. I'm trying to number each fishnet poly based on the zone. Screenshot below is a simple example of what I'm tring to code. (Fishnets have already been intersected with zones, and the topology is correct.)

enter image description here

arcpy.AddField_management("MyFishnet_wZones.shp", "Fishnet_ID", "SHORT", field_is_nullable = "NULLABLE")

nPolygons = int(arcpy.GetCount_management("MyZones.shp").getOutput(0)) # length nPolygons is the total number of zones

for n in range(0, nPolygons):
    counter = 1
    with arcpy.da.UpdateCursor("MyFishnet_wZones.shp", ["Zone_ID", "Fishnet_ID"]) as cursor:
        for row in cursor:
            while row[0] == n + 1: # because Zone_ID starts at 1, not 0
                row[1] = counter
                cursor.updateRow(row)
                counter += 1

And here's the error:

    File "", line X, in <module>
        cursor.updateRow(row)
RuntimeError: The row contains a bad value. 
1

Got it--putting in a SQL statement worked

for n in range(0, nPolygons):
    counter = 1
    sql = '"Zone_ID"= ' + str(n + 1)
    with arcpy.da.UpdateCursor("MyFishnet_wZones.shp", ["Zone_ID", "Fishnet_ID"], sql) as cursor:
        for row in cursor:
            row[1] = counter
            cursor.updateRow(row)
        counter += 1
0

I think that you are being told that you are providing a bad value when the cursor encounters a NULL value in your Zone_ID or other field. However, it may also be that the value you are trying to push into a text field is too long for that field.

I suspect that your answer of restricting the cursor to a subset of rows using a where_clause avoids the error by no longer needing to access the offending row.

0

If you make use of a dictionary you can get your desired results with a single cursor.

di = {}
with arcpy.da.UpdateCursor("MyFishnet_wZones.shp", ["Zone_ID", "Fishnet_ID"]) as curs:
    for zone, fishnet in curs:
        try: lastVal = di [zone]
        except KeyError: lastVal = 1
        row = (zone, lastVal)
        curs.updateRow (row)
        lastVal += 1
        di [zone] = lastVal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.