Sunday 17 April 2016

Removing multiple fields in Arcpy with remove function


I am trying to delete several fields within a feature class using the .remove function but receive the following error when just testing the remove function in the arcpy module;


ERROR 001334: Cannot delete required field Shape


import arcpy

fc="X:\GIS_PROJECTS\Documentation\Test\UA_GDB_1.gdb\Urban"
fields = arcpy.ListFields("X:\GIS_PROJECTS\Documentation\Test\UA_GDB_1.gdb\Urban")


for field in fields:
print field.name

FCfields = [f.name for f in arcpy.ListFields(fc)]
DontDeleteFields = ['UA_ID', 'NAME', 'LSAD', 'LSAD_DESC', 'Join_Number', 'DensitySQMI', 'GeoID2', 'F15Growth','Shape', 'F14Growth', 'GrowthAvg', 'ConFinance500', 'ConFinance400', 'ConFinance300']
fields2Delete = list(set(FCfields) - set(DontDeleteFields))

arcpy.DeleteField_management(fc, fields2Delete)

Answer



What arcpy.ListFields returns is a python list. When you say list.remove(), you're asking for an item to be removed from the Python list. So for starters, if you want to delete a field from the FC, this won't do what you want. Second, the error you're getting states you can only remove 1 items at a time using the python list.remove() function. You've passed it a list of all your fields.


If you want to remove ALL fields in your FC, you can try the following:


fc = "c:/temp/path2/shp.shp"
for f in arcpy.ListFields(fc):
if (f.type == 'OID' or f.type == 'Geometry'):
print("cant delete {}".format(f.name))
else:
arcpy.DeleteField_management(fc, f.name)


Or, perhaps a slightly faster way, but requires you know the shape/oid field name:


fields = [f.name for f in arcpy.ListFields(fc)]
print(fields)
>>[u'ObjectID', u'Shape', u'City', u'Country', u'Name', u'Email', u'Manager']
fields.remove('Shape')
fields.remove('ObjectID')
arcpy.DeleteField_management(fc, fields)

One more code snippet - to get a list of all fields. Take a known list you have and remove those items from the field list and then do your delete with the subset list:



FCfields = [f.name for f in arcpy.ListFields(fc)]
DontDeleteFields = ['Shape_STArea__', 'Shape_STLength__', 'STATE', 'FIPS', 'Shape', 'Shape_Length', 'Shape_Area', 'AreaFT']
fields2Delete = list(set(FCfields) - set(DontDeleteFields))
arcpy.DeleteField_management(fc, fields2Delete)

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