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:
print(total)
out of the loop. This will give you one value which is the total value.print(0)
withcontinue
to skip null values..shx
file so it cannot be loaded.int(sum(filter(None,[f['Value'] for f in layer.getFeatures()])))
which returns the value441
.