Thursday, 18 May 2017

qgis - How to find and replace attribute values based on a list


I have a Shapefile and a list in .csv which contains two columns with names:




  • "Old_name" which contains the old names that already exist in the attribute table of the previously mentioned Shapefile; and

  • "New_name" which contains the updated name.


How can I do this either on ArcGIS, QGIS or with python?


Based on this question I need to use the UpdateCursor function, but how can I use the list in this function?



Answer



Assuming the csv is ready to be consumed by arcpy as a table with two columns named OLD_NAME and NEW_NAME, and following the example provided in the question to get to the source shp in the UpdateCursor.


#create a dictionary of the csv to join to the shapefile
#r[0] is the first item passed to the SearchCursor and used to join to shp
#r[1] is the second item and used for the update

csvDict= dict([(r[0], (r[1])) for r in arcpy.da.SearchCursor(my_csv, ["OLD_NAME","NEW_NAME"])])

with arcpy.da.UpdateCursor(my_shp, ["OLD_NAME","NEW_NAME"]) as cursor:
for row in cursor:
joinFieldValue = row[0] #this is "OLD_NAME" on the shapefile
if row[0] in csvDict: #check to see if old_name exists in new
row[1] = csvDict[joinFieldValue]
else:
row[1] = row[0] #new name is same as the old name
cursor.updateRow(row)

del cursor, row

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...