[GIS] Find and Replace expression needed in Field Calculator ArcGIS 10

arcgis-10.0field-calculatorpython

Looking for the Field Calculator code (Python preferred) to replace the last numeral values in a field using another field's values for entire attribute table. Please see screen shot here: replace values

Best Answer

You could create a Python function for the field calculator using the logic below (using the first record as an example:

>>> a = "EW 140 Rd MF 71"  # your primary field
>>> b = str(71.6)          # your secondary field
>>> a.replace(a.split(" ")[-1], b)  #replace the last entry in the list
'EW 140 Rd MF 71.6'

Or as a def, this might get your further (this example assumes that you are replacing the last entry in string.

def replace_item(primary, secondary):
  '''replace a substring in the primary field with that found in the secondary field:
     string field assumed for primary'''
  a = primary.replace(primary.split(" ")[-1], str(secondary))
  return a

if __name__ == "__main__":
  primary = "EW 140 Rd MF 71"
  secondary = 71.6
  print replace_item(primary, secondary)

and you can run it in standalone mode for testing as shown

EDIT For clarification, when one is doing calculations in the field calculator using Python code blocks, the above code, up to and including the "return a" line is all that is needed. The rest is for running the code as a standlone program in something like Pythonwin. So that code goes in the code block when you toggle on the "show code block" checkbox. To use the above function, make the destination field active and specify the function with the input fields in the expression box. For example:

replace_item(!PRIMARYFLD!, !SECONDARYF!)

would be used assuming the two obviously named fields listed above (ie. PRIMARYFLD and SECONDARYFLD) if they existed in your table. The help files in ArcGIS also indicate that field names must be enclosed in exclamation marks, !. More information can be found in the online help for those wishing to use Python code blocks with the field calculator.

enter image description here

enter image description here