尝试使用游标更改字段中的值

时间:2016-05-22 04:28:58

标签: python cursor arcpy

我们正尝试更改shapefile列中的值,以使用新值创建新字段/列。我们尝试使用搜索和更新光标来完成此操作以及for循环和字段计算器。 有没有人知道如何以简单的方式完成这项工作?

以下是我们脚本的示例,我们尝试转换所有标记为" Montane_Chaparal "在列中输入新值" Dry_Forest "在新专栏

veg = "Cal_Veg.shp"
field = ["WHRNAME"]

therows=arcpy.UpdateCursor(veg, field)

for therow in therows:
    if (therow.getValue(field)==" "):
        therow.setValue("Montane_Chaparral","Dry_Forest")
    therows.updateRow(therow)

print "Done."

我也尝试过:

veg = "Cal_Veg.shp"
with arcpy.da.SearchCursor(veg,["WHRNAME","NewVeg"]) as SCursor:
    for row in SCursor:
        if row[0] == "Montane Chaparral": 
            with arcpy.da.InsertCursor(veg,["NewVeg"]) as ICursor:
                for new_row in ICursor: 
                    NewVeg = "Dry Forest"
                    ICursor.insertRow(new_row)
print "done"

1 个答案:

答案 0 :(得分:0)

出于各种原因,我肯定会为您的脚本推荐更现代的da Update Cursor,但主要是为了速度和效率。

看起来好像你错误地运行嵌套游标,你需要的只是一个更新游标。试试这个。

veg = "Cal_Veg.shp"

with arcpy.da.UpdateCursor(veg,["WHRNAME","NewVeg"]) as cursor:
    for row in cursor:
        if row[0] == "Montane Chaparral": # row[0] references "WHRNAME"
            row[1] = "Dry Forest"         # row[1] references "NewVeg"
        cursor.updateRow(row) 

print "done"