[GIS] Set parameter of field from number to string with Python

arcgis-desktopfield-calculatorpython-parser

Since I realised Python is a very useful tool in ArcMap I don't want to do any workarounds any more. I have a field with is numeric, but I want to perform this calculation in the field calculator on it

def change(GRIDCODE):
    if GRIDCODE == "1":
      return "XZ"
    elif GRIDCODE == "3":
      return "XY"
    elif GRIDCODE == "4":
      return "XX"
    else:
      return "None"

But, the field is a numeric one and it won't let me change it to a string. I suppose I have to change the parameter of the field first. Of course I could add a field, set the parameter of that field to string and then run the code above, a little bit modified, on the shapefile.

But is there a solution where I change the parameter of the field within the code?

Best Answer

If I understand correctly, you want to take an integer field and do some calculations and change the field to a text field, correct?

You cannot do that in the field calculator. However, you can do it in the python window. You would be adding another field, moving and converting values, and then deleting and replacing your GRIDCODE field with another that is text. Be sure you back up before you do anything in case there is an error in my code or your copying. Double check the parameters for the arcpy function as it is coming from my memory.

Update Cursor: http://resources.arcgis.com/en/help/main/10.1/index.html#//018v00000064000000

Add Field: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//001700000047000000

Delete Field: http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//001700000052000000

What you would be looking to do would be something like this:

arcpy.AddField_management("TempField", "TEXT") #create a temp field to hold text values

rows = arcpy.UpdateCursor("YOURLAYER") #create an update cursor to convert and move values
for row in rows: #set an iteration for your rows
    row.TempField = str(row.GRIDCODE) #copy the value over
    rows.updateRow(row) #tell the cursor to update

arcpy.DeleteField_management("GRIDCODE") #remove your integer field
arcpy.AddField_management("GRIDCODE", "TEXT") #create another one with text
#mind you, this moves the field all the way to the right
rows = arcpy.UpdateCursor("YOURLAYER") #create a second update cursor
for row in rows: #set up another iteration
    if row.TempField == "1": #if statement for assignment
       row.GRIDCODE = "BSM"
    elif row.TempField == "3":
       row.GRIDCODE = "BSW"
    elif row.TempField == "4":
       row.GRIDCODE = "BSP"
    else:
       row.GRIDCODE = "None"
    rows.updateRow(row) #update your new text row
arcpy.DeleteField_management("TempField") #clean up the temporary field