ArcPy – Iterating Over Selected Features by the Same ID

arcpycursoriteration

I have a feature class Test_NearestNeighbor_Code. This feature class has 7373 polygon features and a column/ field called osm_id. I want to do a calculation with all features that have the same osm_id. How can I do this in arcpy in an iterative way over all features (without using the ModelBuilder)?

Calculate Field code works, but loop with SearchCursor doesn't, any suggestions for improvement?

Attached the Attribute Table of the feature class Test_NearestNeigbour_Code.

enter image description here

with arcpy.da.SearchCursor("Test_NearestNeighbour_Code", ["osm_id"]) as cursor:
    for row in cursor:
        arcpy.management.CalculateField("Test_NearestNeighbour_Code", "Dispersitätsmaß", "nn_output[1]", "PYTHON3", 'nn_output = arcpy.stats.AverageNearestNeighbor("Test_NearestNeighbour_Code", "EUCLIDEAN_DISTANCE", "NO_REPORT", None)', "DOUBLE", "NO_ENFORCE_DOMAINS")```

Best Answer

Providing your features have unique id field called "UNIQ_ID" and osm_id is integer field the script below should work.

INPUT:

enter image description here

Script:

import arcpy
inLayer = "all_points"
aSet = set(row[0] for row in arcpy.da.TableToNumPyArray(inLayer,"OSM_ID"))
tempFc = "in_memory/selected"
aDict={}
for item in aSet:
    arcpy.AddMessage('Processing item %s' %item)
    arcpy.analysis.Select(inLayer, tempFc, '"osm_id" =%i'%item) #modify query if osm_id is a string
    result = arcpy.stats.AverageNearestNeighbor(tempFc)[1]
    tbl=arcpy.da.TableToNumPyArray(tempFc,"UNIQ_ID")
    for row in tbl:aDict[row[0]]=result #memorize result in dictionary
arcpy.AddMessage('Results transfer...')
with arcpy.da.UpdateCursor(inLayer,("UNIQ_ID","z_score")) as cursor:
    for oid,z in cursor:cursor.updateRow((oid,aDict[oid]))

OUTPUT:

enter image description here

Related Question