I am need to reorder the objectID, but I am having difficulties getting the code correct.
The OriginalOrder.png is what it currently is and the ReOrder.png is what I want. see pictures.
I need the reorder to match the ReOrder picture.
code,
import arcpy
# Define paths
input_fc = r"C:\Temp\Grid.gdb\Clipped_Grid_Polygons"
# Add fields for Max_Longitude and Min_Latitude if they don't already exist
fields = [f.name for f in arcpy.ListFields(input_fc)]
if "Max_Longitude" not in fields:
arcpy.AddField_management(input_fc, "Max_Longitude", "DOUBLE")
if "Min_Latitude" not in fields:
arcpy.AddField_management(input_fc, "Min_Latitude", "DOUBLE")
if "NewIDField" not in fields:
arcpy.AddField_management(input_fc, "NewIDField", "LONG")
# Calculate Max_Longitude and Min_Latitude for each feature
with arcpy.da.UpdateCursor(input_fc, ["OBJECTID", "SHAPE@", "Max_Longitude", "Min_Latitude"]) as cursor:
for row in cursor:
polygon = row[1]
max_longitude = max(point.X for part in polygon for point in part)
min_latitude = min(point.Y for part in polygon for point in part)
row[2] = max_longitude
row[3] = min_latitude
cursor.updateRow(row)
print("Max_Longitude and Min_Latitude fields calculated and updated.")
# Extract the features into a list
features = []
with arcpy.da.SearchCursor(input_fc, ["OBJECTID", "Max_Longitude", "Min_Latitude"]) as cursor:
for row in cursor:
features.append((row[0], row[1], row[2]))
# Sort the list based on Min_Latitude (ascending) and Max_Longitude (descending)
features.sort(key=lambda x: (x[2], -x[1]))
# Create a dictionary to map the new OID values
new_oid_mapping = {oid_tuple[0]: index + 1 for index, oid_tuple in enumerate(features)}
# Update the original feature class with the new NewIDField values based on the sorted order
with arcpy.da.UpdateCursor(input_fc, ["OBJECTID", "NewIDField"]) as cursor:
for row in cursor:
current_oid = row[0]
if current_oid in new_oid_mapping:
row[1] = new_oid_mapping[current_oid]
cursor.updateRow(row)
print("NewIDField values reordered based on Min_Latitude and Max_Longitude sorting.")