How to create a syntax that will replace the same values in different fields

489
2
06-29-2013 09:00 AM
JayMata
New Contributor
Hi,

I am not familiar with Python programming and would appreciate your assitance.

Basically, I have an attribute table of more than 150,000 records and several fields. In 6 of the fields I need to replace a code (or recode) some values for something else. If I use the field calculator I will have to go through each of those fields and would be too cumbersome and tedious. I have the feeling that there is a way to do this simultaneously for all fields but I am not sure how to create the syntax.  I have a few failed trials of comin up with that syntax based on what I have been reading on internet but I am missing something. Any thoughts?

Thanks

Jay

>>> import arcpy
... import os
...
...  !RUseCode02!.replace("999", "9999"), !RUseCode03!.replace("999", "9999"),!RUseCode04!.replace("999", "9999"),
run
Tags (2)
0 Kudos
2 Replies
by Anonymous User
Not applicable
You can either do this using the field calculator, or an update cursor.  Are the RUseCode values a text string or are they integers? If they are numbers, you will not need the quotes around the find or replace values.

Field Calculator:
Pre-logic
def Replace( field, find, replace ):
  if field != find:
    return field
  elif field == find:
    return replace


Expression
Replace( !RUseCode04!, "999", "9999")


[ATTACH=CONFIG]25605[/ATTACH]


Or you could try and use an update cursor to do it all at once.  You can just put all of your fields you want to do this to in the "fields" list.

import arcpy

fc = r'C:\path\to_your\feature_class'
fields = ['RUseCode02', 'RUseCode03', 'RUseCode04']
rows = arcpy.UpdateCursor(fc)
for row in rows:
    for field in fields:
        if row.getValue(field) == '999':
            row.setValue(field, '9999')
    rows.updateRow(row)
del row, rows



I think your original code should have worked by the way...Did you set the parser to Python first and supply those expressions one at a time?
0 Kudos
RhettZufelt
MVP Frequent Contributor
Since you mentioned the field calculator, does that mean you have no issus doing this in ArcMap, or do you need code?

If so, in ArcMap, load the FC, right-click and select open attribute table.  then, in the upper left of the table, under the drop down arrow, you will see Find and Replace.

This will let you find a value and replace with another in all or just selected columns.  Should be what you want unless you are after code.
0 Kudos