Select to view content in your preferred language

Use UpdateCursor to update field based on a change in another field

704
4
11-18-2013 05:38 AM
JensenConnor
Deactivated User
Hi,

I am trying to update a field "TPN" based on another field "PASS_NUM". In my script "TPN" is a newly added number field and thus blank, "PASS_NUM" is also a number field but it contains the wrong numbers. I want to assign values to "TPN" when "PASS_NUM" is no longer equal the the value in the row above it. The feature class table is sorted by "PASS_NUM". See example of table I want to achieve attached: [ATTACH=CONFIG]29165[/ATTACH]

The PASS_NUM field does not increment by 1 each time (i.e. it may skip 7) but the I want to TPN to only go up one. Is this possible using the UpdateCursor in arcpy? Or is there another way to achieve this?

Thanks much!
Tags (2)
0 Kudos
4 Replies
DuncanHornby
MVP Notable Contributor
Jensen,

This can be done in a model or very quickly manually.

  1. Run your table with PASS_NUM through the Summary statistics tool and group by PASS_NUM

  2. Add a new field to this stats table called "X"

  3. copy the FID\objectID into "X", this is your incremental number

  4. Join the stats table to your table based upon PASS_NUM

  5. copy "X" into TPN

Duncan
0 Kudos
MathewCoyle
Honored Contributor
Here is an example using an update cursor. Untested.

import arcpy

table = 'some_table'
last_val = None
count = 0
cursor = sorted(arcpy.da.UpdateCursor(table, ['PASS_NUM', 'TPN']))
for row in cursor:
    if row[0] == last_val:
        row[1] = count
    elif row[0] != last_val:
        count += 1
        row[1] = count
        last_val = row[0]
    else:
        pass
    cursor.updateRow(row)
0 Kudos
JensenConnor
Deactivated User
Matthew,

Thanks for your input. I think this code is very close to working for me. I got a chance to test it out and it throws an AttributeError: 'list' object has no attribute 'updateRow'. The line in question being cursor.updateRow(row). I will continue to play around with this and let you know if I figure anything out. Let me know if you have any ways around this.

Thanks again,
0 Kudos
JensenConnor
Deactivated User
Okay so this probably isn't the best fix but solved by using arcpy.Sort_management(inFeatures, outFeatures, ["PASS_NUM", "ASCENDING"]) and then removing the sorted tag before initializing the update cursor.

Thanks again for the input!
0 Kudos