Geographic Information Systems Asked on December 24, 2020
I’m trying to find and update all empty attributes for all fields in shapefile with “-” by iterate through all fields in shapefile to find which fields are empty.
I tried tp update all empty attributes using the UpdateCursor and it is not done
import arcpy
from arcpy import env
import os
# Set the workspace for the ListFeatureClass function
env.workspace = "c:/base"
fcList = arcpy.ListFeatureClasses()
for fc in fcList:
fields = arcpy.ListFields(fc)
for field in fields:
with arcpy.da.UpdateCursor(fc2, field) as cursor:
for row in cursor:
**#here I donot know how to check blank values in all feileds#**
I am struck here and from here I don’t know how to iterate all rows in all fields and update all empty rows with “-“.
I am attaching example
You don't need to loop through the fields list if you're using an Update Cursor, as stated by Vince. Also you can specify that the ListFields module only returns string fields only.
for fc in fcList:
fields = [f.name for f in arcpy.ListFields(fc, "STRING")]
with arcpy.da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
if row[0] is None or row[0] == " ":
row[0] = "-"
cursor.updateRow(row)
Answered by MacroZED on December 24, 2020
An alternative arcpy approach would be to use the Field Calculator. Although more verbose than a cursor, this method captured my empty strings as non-null values (whereas cursors would not).
Below is a function I would use to replace empty strings with "-" (although as others have stated, if you truly want null values - the correct approach would be to return None
, which are actually null type within the attribute table.
import arcpy , os
def replaceBlanksAsNull(input_fc, use_field):
''' For each field in input fc, replace blanks with null values.
'''
theExpression = "makeNull(!{}!)".format(use_field)
theCode = 'def makeNull(value):n if value == "":n return Nonen else: return value'
arcpy.CalculateField_management(in_table= input_fc,
field= use_field,
expression= theExpression,
expression_type= "PYTHON_9.3",
code_block= theCode)
print('Replaced blanks in {} fc, within field {}'.format(os.path.basename(input_fc), use_field))
Answered by champezius on December 24, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP