Select to view content in your preferred language

Find Min & populate another field

853
3
05-24-2011 09:38 AM
EricMahaffey
Deactivated User
Anyone know how to use Python in the Field Calculator to find the smallest value within a field and use that value to populate every record in another field?

All I have so far is,
Pre-Logic Script Code:
def min(minvalue):
  return minvalue

Expression:
min(!<fieldname>!)

This only returns the same value for each record.
0 Kudos
3 Replies
DarrenWiens2
MVP Honored Contributor
You can use regular geoprocessing tools if you use Python in the field calculator. I'm not sure how to specify "the current feature class" instead of typing the path in the field calculator. Wherever you see <fieldname>, simply type in the field name (no exclamation points or <>s). Keep all of the quotes where they are.

Codeblock:
count = 0
def mini():
    global count
    global value
    global rows
    if count == 0:
        rows = arcpy.SearchCursor("<path to feature class>","","","", "<fieldname> A")
    for each row in rows:
        if count == 0:
            value = row.<fieldname>
            count = 1
    return value

Expression:
mini()
0 Kudos
EricMahaffey
Deactivated User
Thanks Darren,

I tried the code sample inserting my feature class and field where needed but it failed.  I got some feedback from ESRI tech support and they recommended using straight up Python Scripting to do this.  Supposedly it cannot be accomplished using Python in the field calculator.  I've started writing a Python script combing the SearcCursor and UpdateCursor functions.  Making progress.  Being that I'm a rookie at Python I'm still figuring out how to tell SearchCursor to find the Min value, then insert that value into UpdateCursor.  I'll post my code once I wrap it all up.  Thanks for the help.

Eric
0 Kudos
DarrenWiens2
MVP Honored Contributor
ESRI tech support is lying to you. The reason it's not working is because I made a typo in the script (oops). It should be "for row in rows:", not "for each row in rows:". Here is an actual example, that calculates the minimum value for the field "Join_Count" in the feature class "points2sj".
count = 0
def mini():
    global count
    global value
    global rows
    if count == 0:
        rows = arcpy.SearchCursor("H:\GIS_Data\TEMP_GDB.gdb\points2sj","","","", "Join_Count A")
    for row in rows:
        if count == 0:
            value = row.Join_Count
            count = 1
    return value
0 Kudos