[GIS] Deleting many fields from many feature classes using ArcPy

arcpyfield-mappingfields-attributes

I'm currently formatting our GIS data for use in a mobile app. The purpose of altering the data is to reduce the output file size that's imported into the app. I need to delete many fields from many feature classes. I will need to run this script about every two months to provide updated data.

The first part of my script copies the feature classes from our SDE geodatabase to a file geodatabase using arcpy.FeatureClassToFeatureClass_conversion(). This function has a field_mapping parameter which I'm not very familiar with.

What would be the quickest way to delete many fields from many feature classes?

Using the field_mapping parameter, or just using arcpy.DeleteField_management()? I would think field_mapping.


The real problem is that I want to remove around 30 fields from each feature class, and only keep around 4-5.

With field_mapping, (I haven't researched this yet) is there a way to simply state only the fields I want to keep without listing all the fields I want to remove too?

Best Answer

Another alternative is to create a feature layer containing only the fields you want, then use arcpy.CopyFeatures_management() or arcpy.FeatureClassToFeatureClass_conversion() to copy the result to a new feature class.

I've written a function called make_skinny() (with two wrappers, make_skinny_feature_layer() and make_skinny_table_view()) that takes a list of the fieldnames you want to keep and returns a layer/view with only those fields. Also accepts an optional definition query to subset the records.

def make_skinny(is_geo, in_obj, out_obj, keep_fields_list=None, where_clause=''):
    ''' Make an ArcGIS Feature Layer or Table View, containing only the fields
        specified in keep_fields_list, using an optional SQL query. Default
        will create a layer/view with NO fields. '''
    field_info_str = ''
    input_fields = arcpy.ListFields(in_obj)
    if not keep_fields_list:
        keep_fields_list = []
    for field in input_fields:
        if field.name in keep_fields_list:
            field_info_str += field.name + ' ' + field.name + ' VISIBLE;'
        else:
            field_info_str += field.name + ' ' + field.name + ' HIDDEN;'
    field_info_str.rstrip(';')  # Remove trailing semicolon
    if is_geo:
        arcpy.MakeFeatureLayer_management(in_obj, out_obj, where_clause, field_info=field_info_str)
    else:
        arcpy.MakeTableView_management(in_obj, out_obj, where_clause, field_info=field_info_str)
    return out_obj

# Wrapper functions for make_skinny()
def make_skinny_feature_layer(fc, lyr, keep_fields_list=None, where_clause=''):
    return make_skinny(True, fc, lyr, keep_fields_list, where_clause)
def make_skinny_table_view(table, view, keep_fields_list=None, where_clause=''):
    return make_skinny(False, table, view, keep_fields_list, where_clause)
Related Question