HOW TO

Automate deleting fields from a feature class

Last Published: April 25, 2020

Summary

GIS users sometimes need an automated method to delete a specified number of columns or fields on feature classes when simplifying data. Instructions provided describe how to do this using a Python script.

Procedure

The below Python script demonstrates how to automate deleting fields on a feature class based on a specified number, however avoiding the required fields such as the 'SHAPE' column.

  1. Modify the below parameters accordingly:

    workspace ="C:/Delete/fgdb/WGS84.gdb"   
    table = "test"
    max_val = 3


  2. Code:
    import arcpy, os, string

    def DeleteFields(workspace,table,max_val):
    arcpy.env.workspace = workspace
    field_list = arcpy.ListFields(table)
    listx = []
    #Populate list
    for field in field_list:
    listx.append(field.name)

    #Remove required fields
    if 'Shape.STLength()' in listx:
    listx.remove('Shape.STLength()')
    if 'Shape' in listx:
    listx.remove('Shape')
    if 'SHAPE.STLength()' in listx:
    listx.remove('SHAPE.STLength()')
    if 'Shape.STArea()' in listx:
    listx.remove('Shape.STArea()')
    if 'SHAPE.STArea()' in listx:
    listx.remove('SHAPE.STArea()')
    if 'SHAPE.AREA' in listx:
    listx.remove('SHAPE.AREA')
    if 'SHAPE.LEN' in listx:
    listx.remove('SHAPE.LEN')
    if 'SHAPE.LEN' in listx:
    listx.remove('SHAPE.LEN')
    if 'SHAPE' in listx:
    listx.remove('SHAPE')
    if 'Shape' in listx:
    listx.remove('Shape')
    if 'OBJECTID' in listx:
    listx.remove('OBJECTID')
    if 'FID' in listx:
    listx.remove('FID')

    try:
    cnt = 0
    while cnt <= max_val -1 :
    arcpy.DeleteField_management(table, str(listx[cnt]) )
    print "Deleted field {0}".format(listx[cnt])
    cnt +=1
    except:
    print "Warning: Max value may be higher than available fields to delete"

    #clear memory
    del cnt, field, listx, field_list

    if __name__== "__main__":

    workspace ="Database Connections\Connection to test.sde" #workspace
    table = "test2" #name of table
    max_val = 3 #Limiting value. E.g. 3
    DeleteFields(workspace,table,max_val)



Article ID:000011782

Software:
  • Legacy Products
  • ArcMap

Receive notifications and find solutions for new or common issues

Get summarized answers and video solutions from our new AI chatbot.

Download the Esri Support App

Discover more on this topic

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options