"Everything is related to everything else, but near things are more related than distant things"
Population Classification
The script creates a new filed (name: “POP_group”) for the feature class and write a text value (either “High” or “Low”) for each cities that if a city population (e.g. POP1990) is greater than (>=) 50,000 then write “H”, otherwise write “L”.
# Ehsan Momeni
from arcpy import env,ValidateFieldName, ListFields, AddField_management, da # importing requried madules
Input_Path= r"H:\Emomeni\data.gdb" # input gdb path
env.overwriteOutput = True # to overwritght results
env.workspace = Input_Path # setting workspace
fc = "cities" # input feature class
newfield = "POP_group" # new field to be created
fieldtype = "TEXT" # type of the filed that is going to be created
fieldname = ValidateFieldName(newfield) # to determine whether a specific name is valid or not
fieldlist = ListFields(fc) # all fields in the input feature class
fieldnames = []
# trying to see if the field is already exist of not. if not, creates it
for field in fieldlist:
fieldnames.append(field.name)
if fieldname not in fieldnames:
AddField_management(fc, fieldname, fieldtype, "", "", 1) # Creating a new field that accept just 1 letter L/H
print ("%s filed has been added." % newfield)
else:
print ("%s field name already exists." % newfield)
# to search in the first field and update the socond field
fields = ['POP1990', newfield] # first one is the filed we apply condition, the other is the filed we wanna update it
with da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
if row[0] >= 50000: # condition
row[1] = "H"
else:
row[1] = "L"
cursor.updateRow(row)
print ("%s field has been updated." % newfield)