Hello, I am seeking a way to extract top 5 records from a sorted search cursor. According to ESRI, we can use top for sql clause but it is only supported by SQL server. I tried range function (please see below) but it did not work unfortunately.
Thank you in advance for any coding advice!
with arcpy.da.SearchCursor(data, fieldName, sql_clause=(None,'ORDER BY IDA DESC')) as cursor:
for i in range(5):
for row in cursor:
print("IDA value: ", row[1])
Solved! Go to Solution.
# assuming numeric data
# fc = your featureclass
# field = your field
a = [row[0] for row in arcpy.da.SearchCursor(fc, field)]
# assume: a = [9, 5, 3, 2, 10, 22]
sorted(a, reverse=True)[:5]
[22, 10, 9, 5, 3]
# assuming numeric data
# fc = your featureclass
# field = your field
a = [row[0] for row in arcpy.da.SearchCursor(fc, field)]
# assume: a = [9, 5, 3, 2, 10, 22]
sorted(a, reverse=True)[:5]
[22, 10, 9, 5, 3]
Thanks DanPatterson for the solution!
It works well🙂
You were close with your original code, just a couple issues:
with arcpy.da.SearchCursor(data, fieldName, sql_clause=(None,'ORDER BY IDA DESC')) as cursor:
for i in range(5):
print("IDA value: ", next(cursor)[0])
Hi @JoshuaBixby ,
I apology for late reply for your solution - I have realized your message just now.
Kudos for your solution as well🙂