1

I am creating a level of service tool and I need to update the number of lanes field based on the operation type of the road. What I need it to do is: if the operation type equals 2W, then the number of lanes needs to be divided by 2.

for row in rows:
    for field in fields:
        if optype == "2W"
        arcpy.getValue(lanes / 2)

3 Answers 3

2

If you only need to update values where optype=2W, it will be faster to retrieve only those records and modify all of those:

mytable = r"c:\temp\new file geodatabase.gdb\roads"

with arcpy.da.UpdateCursor(mytable, "lanes", "optype='2W'") as cursor:
    for row in cursor:
        row[0] /= 2
        cursor.updateRow(row)

This code uses a da cursor.

2

If you have multiple types of replacements to make, I'd recommend using a cursor with a dictionary (this code is written for 10.1+):

replace_dict = {"2W":2,
                "4w":4,
                #etc.
               }

rows = arcpy.da.UpdateCursor(featureclass,["optypefieldname","lanefieldname"])
for row in rows:
    if row[0] in replace_dict.keys():
        row[1] = row[1]/replace_dict[row[0]]
        rows.updateRow(row)

You could put whatever you want in the dictionary.

1

There are a couple ways to do this in python/arcpy. I would recommend using calculate field on a feature layer with an SQL where clause limiting the records.

Something along these lines will do the trick:

import arcpy

#Input roads feature class
Roadsfc = r"C:\example\data.gdb\roads"

#Field names
OpTypefld = "optype"
Lanefld = "lanes"

#SQL where clause
sql = "{0} = '2W'".format(arcpy.AddFieldDelimiters (Roadsfc, OpTypefld))

#Create feature layer with only '2W' features
arcpy.MakeFeatureLayer_management (Roadsfc, "2WRoadslayer")

#Calculate field
arcpy.CalculateField_management ("2WRoadslayer",
                                 Lanefld,
                                 "[{0}] / 2".format (Lanefld),
                                 "VB")
2
  • Shouldn't the "VB" in CalculateField be "Python_9.3"?
    – recurvata
    Mar 4, 2015 at 16:27
  • 1
    No, I'm using VB code in this instance, as indicated by the brackets in my expression. If I used exclamation points instead then yes, indicating python 9.3 code would do be correct. Mar 4, 2015 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.