Saturday 29 December 2018

arcpy - How to iterate fields and remove Null values and spaces


Is it possible to iterate fields in a table to remove Null values and spaces (where there is no value)? In other words, I would like to replace Null and " " with "" (no space).


Cobbling arcpy scripts, I have this:


import arcpy


fc = "{path to geodatabase and feature class}"
fieldList = arcpy.ListFields(fc)
for field in fieldList:
with arcpy.da.UpdateCursor(fc, [fieldList]) as cursor:
for row in cursor:
if row[0] == None:
row[0] = ''
elif row[0] == ' ':
row[0] = ''
cursor.updateRow(row)


print "Processing complete"

I'm aware of using "remove" in the field calculator, but you have to go field by field. I'd like to do this for the whole table.



Answer



I don't believe that it's possible to calculate for an entire table at once, you will still need to calculate field by field.


As far as actually performing the edit the best way to update the data would be with arcpy.CalculateField_management - which is effectively the field calculator in your Python script - rather than an Update Cursor (which has to operate row at a time). You can use a Python expression in arcpy.CalculateField_management (or the field calculator itself) to check a string and return the updated string, for example:


(!field_name! or "").strip() # will also strip the trailing spaces

Which you can throw at arcpy.CalculateField_management in a script;



import arcpy

fc = "{path to geodatabase and feature class}"
fieldList = arcpy.ListFields(fc, field_type="String") # don't want to try this on an integer

for field in fieldList:
expression = """(!{}! or "").strip()""".format(field.name)
arcpy.CalculateField_management(fc, field.name, expression, "PYTHON_9.3")

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...