# Excluding zero values in proportion calculation in QGIS

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?

Use this expression:

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

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.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")
``````