Skip to main content
2 of 3
added 844 characters in body
MrXsquared
  • 35.6k
  • 22
  • 71
  • 121

For PyQGIS 3 this might be the easiest way to delete a single field:

# Get a layer object and enter edit mode:
my_vectorlayer = iface.activeLayer()
with edit(my_vectorlayer):
    # Get the field index by its name:
    my_field = my_vectorlayer.fields().indexFromName('name of field you want to delete')
    # Delete the field by its index, note that it has to be in a list:
    my_vectorlayer.dataProvider().deleteAttributes([my_field])
# Update the fields, so the changes are recognized:
my_vectorlayer.updateFields()

Or if you want to delete multiple fields at once, you can go for this slightly modified:

# Get a layer object:
my_vectorlayer = iface.activeLayer()
# Create a list of the fieldnames you want to delete:
fieldnames_to_delete = ['field_a','field_c']
# Enter Edit mode
with edit(my_vectorlayer):
    # Create empty list we will fill with the fieldindexes
    fields_to_delete = []
    # Get the field index by its name:
    for fieldname_to_delete in fieldnames_to_delete:
        fields_to_delete.append(my_vectorlayer.fields().indexFromName(fieldname_to_delete))
    # Delete the fields by their indexes, note that it has to be a list:
    my_vectorlayer.dataProvider().deleteAttributes(fields_to_delete)
# Update the fields, so the changes are recognized:
my_vectorlayer.updateFields()
MrXsquared
  • 35.6k
  • 22
  • 71
  • 121