Find fields in a feature class that have only nulls with arcpy

A friend asked to help to write a tiny script that would list fields that contain only nulls (i.e., no data at all). So, basically find any columns that were not populated with any value for any feature since their creation time.

Quite easy and quick to do with arcpy.


import arcpy
fc = r"C:\Users\user\Documents\ArcGIS\Default.gdb\_DeleteColumns"

#getting list of fields with nulls allowed (those that don't allow nulls won't have
#nulls so we can skip them already now
not_null_fields = [field.name for field in arcpy.ListFields(fc) if field.isNullable != "False"]

#getting a dict {field_name : [list of all values]}
fields_dict = {field: list(set([feature[not_null_fields.index(field)] for feature in arcpy.da.SearchCursor(fc,not_null_fields)])) for field in not_null_fields}

#finding out which fields contain only None (null in Python terms)
fields_to_remove = [k for k,v in fields_dict.iteritems() if v == [None]]

#remove fields from the fc that contain only Null values
for field in fields_to_remove:
arcpy.DeleteField_management(fc,field)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s