Friday, 3 June 2016

How to use QGIS field calculator in python?


I would like to use QGIS Field Calculator in Python to update the existing column based on certain conditions?


How can I do this?



Answer



There is no prebuilt class to do the magic the field calculator does (I am planning on adding it at some stage) however it's quite simple:


expression = QgsExpression("1 + 1")
# This allows field lookup
index = layer.fieldNameIndex("UpdateField")
expression.prepare(layer.pendingFields())
layer.startEditing()

for feature in layer.getFeatures():
value = expression.evaluate(feature)
layer.changeAttributeValue(feature.id(), index, value)

layer.commitChanges()

A couple of notes: We are using changeAttributeValue because it's faster but does require use to use the feature id and field index, another way which might be as fast but is clearer to read is:


expression = QgsExpression("1 + 1")
# This allows field lookup
expression.prepare(layer.pendingFields())


layer.startEditing()
for feature in layer.getFeatures():
value = expression.evaluate(feature)
feature["UpdateField"] = value
layer.updateFeature(feature)

layer.commitChanges()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...