PyQGIS – Summing Values in One Field

aggregatefields-attributespyqgissummarizing

In QGIS 2.18 there is a shapefile with three fields accordingly

id Type Value
1 a 5
2 b NULL
3 c 1
4 d 6
5 e NULL

I want to get the total sum of all values in the field "Value". How can I achieve that in the Python Console?

The field "Value" maintains two types of data int and NULL.

I was trying with a while-loop but it does not work

layer = qgis.utils.iface.activeLayer()

if not layer.isValid():
    raise Exception('Layer is not valid')

features = layer.getFeatures()

for feat in features:
    attr = feat.attributes()[2]
    
    if attr == NULL:
        continue

    else:
        total = 0
        index = 0
        while index < layer.featureCount():
            total = total + int(attr)
            index = index + 1
return(total)

How to achieve one number that gives the total sum of a whole field exclusive NULL-values?

After executing @ahmadhanb's solution I received a correct number but
somehow with a strange output type, when print (type(sum(total))) it gives me
<type 'NoneType'>. What could be a problem?


References:

Best Answer

In programming, there are several ways of solving a problem.

That's also the case for summing values of a field in QGIS. But there is one that is the recommended way, truly leveraging the PyQGIS API.

Aggregating field values using PyQGIS

To get the sum of a field you can use:

total_sum = layer.aggregate(QgsAggregateCalculator.Sum, "my_field_name")

Simpler and faster.

Note: Since the result is a tuple (result_value, boolean_result), you just call total_sum[0] and you are done.


Read the docs to know the list of aggregate types you can use.

You can even pass filter expressions to the aggregates. Really powerful.


Note: this is available since QGIS 2.16.

Related Question