I have multiple geopackages with columns containing a mix of 0 and NULL fields. I want to remove these columns where there is no value above 0. I cannot do this manually as each geopackage has 90-100 columns.


1 Answer 1


Doing this requires iterating through the layer, checking every value in the field (column) to find the empty fields, and then deleting the empty fields. You can use a pyqgis script like this, run from Python console (this one operates on the currently selected layer):

layer = iface.activeLayer()
fieldsToDelete = []

nulls = 0 # nulls = Zeroes and NULLs
for field in layer.fields(): # repeat for every field
    for feature in layer.getFeatures(): # check every feature
        # if value is 0 or NULL, counts towards "nulls"
        if (feature.attribute(field.name())== NULL) or (feature.attribute(field.name())== 0):
            nulls += 1
    if nulls == layer.featureCount(): # if ALL features are 0/null, drop the field
    # reset for the next field
    nulls = 0

# apply changes (never delete fields while iterating over the layer)
for empty_field in fieldsToDelete:
    print(f'Field {empty_field} deleted')

There is probably a better/faster way, but this works for me...

Not the answer you're looking for? Browse other questions tagged or ask your own question.