29 Apr 2016

Insert Curse Here: How to sort within the data access module's insert cursor in arcpy

Submitted by geobug

This is a nitty gritty post regarding the arcpy package for ArcGIS. If that doesn't interest you, feel free to wander off and get yourself a sandwich or something.

An arcpy question popped up over on gis.stackexchange about how to sort an attribute table by one field, and then add sequential numbers to a second field based on that sorting.

So what this user basically wanted to do was sort a list of cities alphabetically and assign them a number so Anaheim gets 1, Bakersfield gets 2, and Compton gets 3. The answer to the question was a pretty simple one. It's five lines of code and an update cursor to the rescue... Ta-da-da-da! But which update cursor?

If you're new to python, a cursor is something that goes through a dataset (a table, a feature class, whatever) and looks it one row at a time until it gets to the end.

They're dead useful. But as it happens, there's two versions of each cursor in the arcpy site package, which tends to confuse new coders.

Prior to ArcGIS 10.1, the update cursor in the arcpy package was a pretty simple thing, and when you defined your cursor you could choose how you wanted to sort your rows as an optional variable. It had some draw backs, though. It was a bear to work with if you needed a join on your input dataset, you couldn't access certain kinds of fields (nothing fancy like the geometry or a blob field), and it wasn't wildly efficient with your processor's time.

At 10.1, we got the data access module and a whole new sunshiny world appeared before us. Joined fields were a breeze, it was fast, you could dig around in the geometry with your cursor, which was huge, but in the process, we lost the sort functionality. (This makes sense when you think about it. If you specified a field like "SHAPE" as your sort field, arcpy would probably have a few choice words to shoot back at you in the form of a bright red error message.)

The old cursor is still there, and you're still welcome to use it, so it's perfect for my friend above who wants to make a list of glamorous cities to visit in California, but what if you wanted to sort and hit the geometry too? How would you do it?

Here's my solution. Below is a little function that uses arcpy.da.UpdateCursor to go through a list of points and number them from west to east.