Arsip

Posts Tagged ‘QgsExpression’

QgsExpression with Python

In QGIS, there is this cool feature called by Expression. I use it mostly on Field Calculator in attribute table. There are some places that you can find also. You can read more about this Expression here.

This week, I tried to use it in Python. It turned out very simple (of course, I need to Google it here and there first how to use it). The class name is QgsExpression. You can import it from qgis.core. Below a sample code how to use it:

from qgis.core import QgsField, QgsExpression
def sum_fields(layer, output_field_name, input_fields):
    """Sum the value of input_fields and put it as output_field.

    :param layer: The vector layer.
    :type layer: QgsVectorLayer

    :param output_field_name: The output field name.
    :type output_field_name: str

    :param input_fields: List of input fields' name.
    :type input_fields: list
    """
    # Creating expression
    string_expression = ' + '.join(input_fields)
    sum_expression = QgsExpression(string_expression)
    sum_expression.prepare(layer.pendingFields())

    # Get the output field index
    output_idx = layer.fieldNameIndex(output_field_name)
    # Output index is not found
    if output_idx == -1:
        output_field = QgsField(output_field_name, QVariant.Double)
        layer.startEditing()
        layer.dataProvider().addAttributes([output_field])
        layer.commitChanges()
        output_idx = layer.fieldNameIndex(output_field_name)

    layer.startEditing()
    # Iterate to all features
    for feature in layer.getFeatures():
        feature[output_idx] = sum_expression.evaluate(feature)
        layer.updateFeature(feature)

    layer.commitChanges()

The code above is a function to sum the value in list of fields (input_fields) into an output field (output_field_name) in a layer.

Basically, you just need to create the expression, and evaluate it to get the value from the expression. In this doc, I found out that using prepare will make the evaluation faster for many features.