7

I'm trying to calculate the proportion of seven fields. It is easy to divide the sum of seven fields by seven, but since some fields have zero values, I want to exclude them from the calculation.

For example, if two of the values are zero, I want to divide the sum by five in that row. How can this process be done in the Field Calculator?

enter image description here

2 Answers 2

8

Use this expression:

array_mean(
    array_remove_all(
        array("field1", "field2", ...),
        0 -- set here the value to be excluded
        )
    )
1
  • 4
    Or easier, using array_mean function: array_mean( array_remove_all( array( "field1", "field2", ...),0))
    – Babel
    Jun 19, 2022 at 10:27
1

Perhaps somebody will find this PyQGIS solution helpful:

from qgis.core import QgsProject
from statistics import mean

def mean_without_zeros(layer_name, list_of_fields, output_field):
    layer = QgsProject.instance().mapLayersByName(layer_name)[0]
    fields_names = layer.fields().names()
    
    if not output_field in fields_names:
        new_field = QgsField(output_field, QVariant.Double)
        layer.dataProvider().addAttributes([new_field])
        layer.updateFields()
    
    layer.startEditing()
    
    for feature in layer.getFeatures():
        field_values = [feature.attribute(field.name()) for field in feature.fields() if field.name() in target_fields]
        field_values_no_zeros = filter(lambda x: x > 0, field_values)
    
        feature[output_field] = mean(list(field_values_no_zeros))

        layer.updateFeature(feature)

    layer.commitChanges()
    
    return

mean_without_zeros('data', ["VALUE1", "VALUE2", "VALUE3"], "MEANVAL")

result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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