ArcPy: define fields to keep, delete all other fields in a feature class

by maycca   Last Updated September 11, 2019 14:22 PM - source

I am trying to write a script to read a feature class, list all fields and keep only specic ones. I.e. drop all remaining columns.

I guess that pseudo code should be:

  1. allFields = create list of all fields
  2. fieldToKeep = define list of fields to keep (manually)
  3. fieldsToDrop = different items between list 1 and list2 = to remove
  4. execute arcpy.DeleteField_management(inFC, fieldsToDrop) to remove uncecessary fields

Should be pretty simple, but I cannot figure out steps and conditioning in correct order?

# Input point data
inFC= "inFC"

# CHeck if field exist,if yes, delete the field
allFields = arcpy.ListFields(inFC)

fieldsToKeep = ["OBJECTID", "Shape", "Country", "manualChange"]
fieldsToDrop = []  # define new empty list

for field in allFields:   # how to difference two lists?
    if not field in fieldsToKeep:
        fields.remove(field)

# Execute DeleteField
arcpy.DeleteField_management(inFC, fieldsToDrop)


Answers 1


You can use python sets to calculate fieldsToDrop and loop over it to remove the desired fields like so:

# Input point data
inFC= "inFC"

# CHeck if field exist,if yes, delete the field
allFields = [f.name for f in arcpy.ListFields(inFC)]

fieldsToKeep = ["OBJECTID", "Shape", "Country", "manualChange"]
fieldsToDrop = list(set(allFields) - set(fieldsToKeep))

# Execute DeleteField
arcpy.DeleteField_management(inFC, fieldsToDrop)

See also Get difference between two lists

umbe1987
umbe1987
September 11, 2019 13:40 PM

Related Questions


Creating Field Mapping Parameter in Arcpy Script

Updated May 31, 2019 15:22 PM

CalculateField_management data value type error

Updated July 07, 2017 16:22 PM

How to calculate field in arcpy.Append_management

Updated April 26, 2019 18:22 PM

Script not working as expected

Updated June 12, 2015 22:09 PM