0

Is there any python code that:

1st, sort a column (example name by alphabet)

2nd, grab the first cell of sorted column and assigned it to a variable like A=..

I need all of this to be done in field calculator and inside show block. Please give me a sample or help.

2
  • 4
    Field calculator operates on a row at a time, but your sort involves looking at all table rows. Why do you want to do this in Field Calculator? If in ModelBuilder, the tool you want is Calculate Value. Nov 19, 2015 at 18:09
  • I have a column in feature,which some of cells are Null, but the rest of values are the same. However, I used this column as part of my code, by sorting it, I can use the first value of the cell and assigned it to a variable. Then,I will be able to use it and do other calculation which I need to do.
    – Koush
    Nov 19, 2015 at 18:23

3 Answers 3

3

You'll want to use the data access search cursor (requires ArcGIS 10.1+) for this task, and its sql clause functionality. The sql clause allows for sorting.

Here's the python code that assigns the first non-null value in the sorted field to the varaible var:

#Path to feature class
fc = r"C:\Path\To.gdb\Feature Class" 
#Field name
fld = "Field_Name"

sqlClause = (None, "ORDER BY {0} ASC".format (fld))

with arcpy.da.SearchCursor (fc, fld, sql_clause = sqlClause) as cursor:
    for val, in cursor:
        if val:
            break
del cursor

example:

enter image description here

I recommend doing this outside of the field calculator, and instead as a python script imported into ModelBuilder, so that each row calculated doesn't create a new cursor.

3

Given all what I've seen so far it seems to me the best approach is to use the Calculate Value tool in ModelBuilder.

Expression:

getval(r"%featureclass%", "FIELDNAME")

Code Block:

import arcpy
def getval(fc, fld):
    # get the first non-null field value
    where = "{} IS NOT NULL".format(fld)
    val = arcpy.da.SearchCursor(fc, fld, where).next()[0]
    return val

Data Type:

 Any value
1

instead of sorting,

  1. do a select by attribute > [field] is not NULL.
  2. then on the selected table 'collect a value' it will naturally take the value in the first row of your field since all the Nulls are selected out that should be fine.
  3. Then do a select attribute again and choose 'CLEAR SELECTION' to make sure the rest of your analysis doesn't happen on a subset of your data. Make the 2nd step a precondition of the 3rd step so that the selection is not cleared before the value is collected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.