Skip to content

Instantly share code, notes, and snippets.

@clarkhacks
Created March 27, 2023 20:36
Show Gist options
  • Save clarkhacks/60a975c1f02fbcef4e89971d926da3ab to your computer and use it in GitHub Desktop.
Save clarkhacks/60a975c1f02fbcef4e89971d926da3ab to your computer and use it in GitHub Desktop.
import arcpy
# input table and field name to modify
table = r"path\to\your\table"
field = "your_field_name"
# loop through each row and modify the field value
with arcpy.da.UpdateCursor(table, [field]) as cursor:
for row in cursor:
# get the original field value
orig_value = row[0]
# split the value by commas and keep the first element (city name)
city_name = orig_value.split(",")[0]
# set the modified value back in the field
row[0] = city_name
cursor.updateRow(row)
# without modifying the existing data.
import arcpy
# Set input table and field names
input_table = r"path/to/your/table"
input_field = "original_field_name"
new_field = "modified_field_name"
# Add new field to hold modified city names
arcpy.AddField_management(input_table, new_field, "TEXT", field_length=50)
# Update new field with modified city names
with arcpy.da.UpdateCursor(input_table, [input_field, new_field]) as cursor:
for row in cursor:
# Get city name by splitting original field value
city = row[0].split(",")[0]
# Remove any leading or trailing spaces
city = city.strip()
# Update new field with modified city name
row[1] = city
cursor.updateRow(row)
@clarkhacks
Copy link
Author

This code creates a new text field with a length of 50 characters and then uses an update cursor to loop through each row of the input table. For each row, it splits the value in the original field by commas, gets the first value (the city), removes any leading or trailing spaces, and then updates the new field with the modified city name. The original data remains unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment