11

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

How can I do this?

Taras
  • 32,823
  • 4
  • 66
  • 137
Pugazh
  • 607
  • 6
  • 17

1 Answers1

8

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()

Taras
  • 32,823
  • 4
  • 66
  • 137
Nathan W
  • 34,706
  • 5
  • 97
  • 148
  • I am testing this code, but I get an error on the expression.prepareFields(layer.pendingFields()) line? QgsExpression' object has no attribute 'prepareFields' – kflaw Mar 09 '15 at 18:44
  • please use 'prepare' instead of 'prepareFields' – Pugazh Apr 07 '15 at 11:52