Now I know there are several ways to tackle this problem but so far none of the following worked for me. I got a huge attribute table out of various spatial joins so pretty much all of the fields have NULL values in some rows. This table will be processed and new fields are going to be calculated programatically so the solution involving the coalesce function is out of the race because the expressions for the following calculations are complex enough and I don't want to do all that typing. So here are my failed attempts of fiddeling together a function that i can use inline:
def replaceNulls(layer):
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
with edit(layer):
for field in layer.fields().names():
for feat in layer.getFeatures():
expr = QgsExpression('if({f} is null,0,{f})'.format(f=field))
feat[field] = expr.evaluate(context)
layer.updateFeature(feat)
Using an expression from this answer replaces ALL the fields with 0 and some with field
- independent of their field type.
def replaceNulls(layer):
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))
with edit(layer):
for field in layer.fields().names():
for feat in layer.getFeatures():
expr = QgsExpression('case when {f} is null then 0 else {f} end'.format(f=field))
feat[field] = expr.evaluate(context)
layer.updateFeature(feat)
This function replaces all values that are NOT NULL with 0 for some reason all though it is said here that:
The expression syntax is exactly the same as in the field calculator GUI. So you can test them in the GIU first, before copying them into your PyQGIS script.
If that is the case what am I missing out on? The same source also mentions a more pythonic way but how to if feat[field] is None:
when the NULL value is still a QVariant?
TL;DR: replace(NULL,0)
. How?