For PyQGIS 3 this might be the easiest way to delete a single fieldsingle 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 oncedelete 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 = []
# GetIterate over the fieldlist indexof byfieldnames itsand name:get the indexes
for fieldname_to_delete in fieldnames_to_delete:
fields_to_delete.append(# Get the field index by its name:
fieldindex_to_delete = my_vectorlayer.fields().indexFromName(fieldname_to_delete)
# You can also check if the field exists
if fieldindex_to_delete == -1:
# If it does not exist, just skip it and go to the next one. This may prevent a crash or error :)
continue
# Append the index to the list
fields_to_delete.append(fieldindex_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()