Populate one field based on second

516
3
Jump to solution
11-04-2010 06:54 AM
PamelaLinson-DeVore
New Contributor
This may be simple but I am only a beginner.  Does anyone have a Python script to populate a field based on the code of another field in the same table?  Or do have any recommendations where I might find a script?

Thank you
Pam
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
curtvprice
MVP Esteemed Contributor
Does anyone have a Python script to populate a field based on the code of another field in the same table?


This can be done a lot faster by using the CalculateField tool than with a cursor:

Expresson: NEWFIELD =
f(!CODEFIELD!)


Code block:
def f(code):
  codelist = ['a','b','c']
  valuelist = [10,20,30]
  value = valuelist[codelist.index(code)] 
  return value


Language: "PYTHON"

But I need to say that generally the best way to do this is to have a lookup table and use a join and Calculate Field to calculate values over.

View solution in original post

0 Kudos
3 Replies
RandyKreuziger
Occasional Contributor III
Hi Pam,
  Welcome.  Try posting your question under the geoprocessing forum.  This forum is more for asking questions about ESRI Map Data.
0 Kudos
StephenBarrow
New Contributor
This may be simple but I am only a beginner.  Does anyone have a Python script to populate a field based on the code of another field in the same table?  Or do have any recommendations where I might find a script?

Thank you
Pam


Hi Pam

In python use an updateCursor to access and update the rows then work row by row making your changes as required.  Here is something to get you started:

import arcpy
cur = arcpy.UpdateCursor(r"c:\your file") #put in your file path here
for row in cur:
  row.fieldName1 = row.fieldName2  #here I am copying the data from one field to another, just add your own code here.
  cur.updateRow(row) #transfer the row changes from memory to the table

Hope this helps

Stephen
0 Kudos
curtvprice
MVP Esteemed Contributor
Does anyone have a Python script to populate a field based on the code of another field in the same table?


This can be done a lot faster by using the CalculateField tool than with a cursor:

Expresson: NEWFIELD =
f(!CODEFIELD!)


Code block:
def f(code):
  codelist = ['a','b','c']
  valuelist = [10,20,30]
  value = valuelist[codelist.index(code)] 
  return value


Language: "PYTHON"

But I need to say that generally the best way to do this is to have a lookup table and use a join and Calculate Field to calculate values over.
0 Kudos