-1

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

1 Answer 1

3

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
        fieldsToDelete.append(field.name())
    # reset for the next field
    nulls = 0

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

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.