Select to view content in your preferred language

How to permanently reclassify the attribute table records

4039
3
Jump to solution
02-18-2015 11:55 AM
AhmadSALEH1
Frequent Contributor

Hi All,

How to permanently reclassify "Sort" the attribute table records based on a field value ? I try the geoprocessing tool Sort (Data Management), but this tool always need to write a new output feature or table with a correct values, what I need is to permanently sort the value on the same table or feature class.

 

Regards,

Ahmad

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
DarrenWiens2
MVP Honored Contributor

I'll preface this by saying this is a dangerous script, not to be attempted unless you know what you're doing. It will overwrite your original data, so make a backup.

You can permanently sort your records using the following script. Beware that once sorted and updated, the object ID will update from 0 - end.

>>> data = []
>>> with arcpy.da.SearchCursor("csv_points","*") as cursor:
...    for row in cursor:
...        data.append(row)
...       
>>> data.sort(key=lambda tup: tup[6]) # sorts based on the 7th field, change if you want.
>>> count = 0
>>> with arcpy.da.UpdateCursor("csv_points","*") as cursor:
...    for row in cursor:
...        row = data[count]
...        count += 1
...        cursor.updateRow(row)

View solution in original post

0 Kudos
3 Replies
ChrisDonohue__GISP
MVP Alum

Question - what is driving the need to have the attribute table permanently sorted?  I ask as the attribute table is typically sorted on a "as needed basis", as permanently sorting it can be a bit of work (and will likely get undone the moment one edits a feature class).   However, there are various "as needed" solutions depending upon why it needs to be sorted.  The best solution will depend on the reason why it needs to be sorted.

Chris Donohue, GISP

0 Kudos
DarrenWiens2
MVP Honored Contributor

I'll preface this by saying this is a dangerous script, not to be attempted unless you know what you're doing. It will overwrite your original data, so make a backup.

You can permanently sort your records using the following script. Beware that once sorted and updated, the object ID will update from 0 - end.

>>> data = []
>>> with arcpy.da.SearchCursor("csv_points","*") as cursor:
...    for row in cursor:
...        data.append(row)
...       
>>> data.sort(key=lambda tup: tup[6]) # sorts based on the 7th field, change if you want.
>>> count = 0
>>> with arcpy.da.UpdateCursor("csv_points","*") as cursor:
...    for row in cursor:
...        row = data[count]
...        count += 1
...        cursor.updateRow(row)
0 Kudos
AhmadSALEH1
Frequent Contributor

Many thanks darren It worked well with me

0 Kudos