3

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)
1
  • 2
    ListFields is listing field objects which has properties like name and type. Try: fields_to_drop = [f.name for f in arcpy.ListFields(inFC) if f.type not in ('Geometry','OID') and f.name not in ["Country", "manualChange"]]
    – BERA
    Sep 11, 2019 at 13:52

1 Answer 1

7

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

1
  • 4
    Performance tip: I've found that DeleteField can take an inordinate amount of time on large datasets, especially if deleting many fields. It's often much faster instead to utilize FieldInfo to select fields of interest, create a temporary layer, save it to a new dataset, delete the old dataset, and rename the new dataset to match the old.
    – Tom
    Sep 11, 2019 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.