Geographic Information Systems Asked on November 1, 2021
I am trying to update a field in an attribute table in a feature Layer with arcpy.da.UpdateCursor
.
I am running the Python script as part of a model in ArcGIS 10.6.
But I am lacking some of the basic concept of how arcpy.da.UpdateCursor
edits the attribute table of my feature layer.
My Python script is based on https://community.esri.com/thread/237881-how-to-calculate-a-field-using-other-field:
import arcpy
import os
# function returns list of unique values in a given field of a table
def unique_values(table , field):
with arcpy.da.SearchCursor(table, [field]) as cursor:
return sorted({row[0] for row in cursor})
fc = os.path.abspath(arcpy.GetParameterAsText(0))
lst = unique_values(fc, 'NetworkID')
with arcpy.da.UpdateCursor(fc, ['NetworkID', 'outlet']) as cursor:
for row in cursor:
row[1] = lst.index(row[0])
cursor.updateRow(row)
The field I want to edit is called ‘outlet’ and mostly consists of NULLs and it should be edited based on the value in ‘NetworkID’. NetworkID has no NULLS and categorizes the outlets into groups (lets call them networkgroups).
How do I get all values in outlet of the same networkgroup to have a value based on the only not null value in outlet in the same networkgroup?
For example:
outlet NetworkID
null 1
null 1
null 1
S_21 1 #<- as this is the only non NULL in the networkgroup '1' I want to use it to define the other outlet in the same networkgroup '1'
null 2
S_45 2
... ...
should look like:
outlet NetworkID
S_21 1
S_21 1
S_21 1
S_21 1
S_45 2
S_45 2
... ...
If you have a table like your first example then use a dictionary to fix it:
import arcpy
fc = r'C:somedb.gdbsomefeatureclass'
d = {nid:outlet for nid,outlet in arcpy.da.SearchCursor(in_table=fc, field_names=['NetworkID', 'outlet'], where_clause="""{0} is not None""".format(datasource=fc,field='NetworkID'))}
with arcpy.da.UpdateCursor(fc,['NetworkID', 'outlet']) as cursor:
for row in cursor:
if row[0] in d:
row[1] = d[row[1]]
cursor.updateRow(row)
Answered by BERA on November 1, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP