11

I would like to use Field Calculator in PyQGIS to update the existing column based on certain conditions.

How can I do this?

2
  • I think this answer might help.
    – lrssvt
    Commented Dec 3, 2014 at 13:46
  • I agreed, you don't need the Field Calculator with PyQGIS, everything can be done in Python (look at Using Vector Layers)
    – gene
    Commented Dec 3, 2014 at 19:16

1 Answer 1

9

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()
3
  • I am testing this code, but I get an error on the expression.prepareFields(layer.pendingFields()) line? QgsExpression' object has no attribute 'prepareFields'
    – kflaw
    Commented Mar 9, 2015 at 18:44
  • 1
    please use 'prepare' instead of 'prepareFields'
    – Pugazh
    Commented Apr 7, 2015 at 11:52
  • For Qgis 3 and later see: docs.qgis.org/latest/en/docs/pyqgis_developer_cookbook/… I think the above really only apply to qgis 2
    – LeasMaps
    Commented 16 hours ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.