PyQGIS: Calculate Geometry and Field Values with the QGIS Python API


Using attribute fields in calculations is one of the most fundamental components of GIS analysis. Field calculations are what makes it possible to take data linked to spatial features and analyze features based on what they are and where they are.

Manually performing field calculations in QGIS can be tedious, especially if you’re working with big data and have a lot of calculations to do. While the QGIS field calculator is an adequate tool, it doesn’t give you many batch processing options. This is where calculating field values with the QGIS Python API (PyQGIS) can really help you out.

With the PyQGIS API you can easily automate any operation you could do in the QGIS field calculator. To calculate field values with PyQGIS all you need to do is set up an expression and apply that expression to the attribute table of your vector file.

This article will demonstrate how to use PyQGIS field calculations to calculate geometry and perform mathematical operations. For additional examples with data and code provided check out the full PyQGIS course. You can also watch the video of this demonstration.

1. Load a Vector Layer

To start, you’ll need to load a vector layer. I’m loading a shapefile with line features that represent stream segments. Load the file as a QgsVectorLayer.

fn = 'path/to/file'
layer = QgsVectorLayer(fn, '', 'ogr')

2. Create a New Field

We’re going to need a new field (i.e. column) in the attribute table to store the result of our calculation. To do this, get the layer’s data provider, which will give you access to the attributes, then add a new attribute.

Here, I’m adding two fields named ‘len_test_m’ and ‘calc’. The field ‘len_test_m’ will hold the the length of each line in my vector file after I calculate geometry. The field ‘calc’ will hold the result of a simple mathematical calculation that I’ll describe below. Values for each field are decimal numbers so the type is set to a double.

pv = layer.dataProvider()
pv.addAttributes([QgsField('len_test_m', QVariant.Double), QgsField('calc', QVariant.Double)])

After adding the fields update the layer for the changes to take effect.

layer.updateFields()

3. Define Field Calculator Expressions

Once the fields are added we can define the expressions used to populate each field. For ‘len_test_m’, I’m going to calculate the length of each line feature. For ‘calc’, I’m going to divide one column by another.

Calculate Geometry

The expression to calculate the length of line in QGIS is simple. Just use the $lenght property. To do this properly you’ll need to set it up as a QgsExpression as demonstrated below.

expression1 = QgsExpression('$length')

Notice how the expression is wrapped in single quotes (‘ ‘).

Field Calculations

Using existing field values in a calculation is quite simple. Make sure field names are designated by double quotes (” “) and the entire expression is wrapped in single quotes (‘ ‘). For this example, I’m going to divide one field by another. This same procedure will work for other mathematical operations and more complicated expressions.

expression2 = QgsExpression('"field1"/"field2"')

4. Set the Context for the Calculation

This is a very important step. So far we have created the fields that will be populated by our calculations and the expressions to perform the calculations. No we need to specify which layer to perform the expression on. This is done by creating a QgsExpressionContext object, which we will pass to when we calculate the expression.

First create the QgsExpressionContext object. Then give it the scope of the layer you’re working with.

context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(layer))

Now we’re ready to do the calculation.

5. Perform the Field Calculation

To perform the calculation, turn on editing for the layer then loop through each feature in the layer and apply the expression. After the expression is applied be sure to update the feature.

For this example, I’m going to perform each field calculation individually. You may want to experiment with putting multiple field calculations in the same loop. Theoretically, it should work as long as your calculations don’t depend on the results of another calculation.

Geometry Calculation

with edit(layer):
    for f in layer.getFeatures():
        context.setFeature(f)
        f['len_test_m'] = expression1.evaluate(context)
        layer.updateFeature(f)

Field Math Calculation

with edit(layer):
    for f in layer.getFeatures():
        context.setFeature(f)
        f['calc'] = expression2.evaluate(context)
        layer.updateFeature(f)

6. Check Your Work

After running your expression for the first time it’s always a good idea to evaluate the results to be sure they are correct. You don’t want to use your new value in other calculations only to find out something went wrong (usually human error) during the calculation. No that this has ever happened to me . . cough, cough.

Conclusion

Calculating field values and feature geometry is a fundamental practice in GIS. With what you’ve learned in this article you can now automate this process to greatly increase the volume of data you can analyze. This should give you the basics of how to automate geometry calculation and field calculations with PyQGIS. If you’re looking for additional help and data to practice with, check out our full PyQGIS course where we provide data, step-by-step video instruction, and code for each lesson.

Watch the Video

Video to calculate geometry and use field calculator with PyQGIS.

Konrad Hafen

Konrad has a Master's Degree in Ecology and a Doctorate Degree in Water Resources and has been performing geospatial analysis and writing code (in multiple programming languages) for over a decade. He writes code to develop models and analysis workflows to predict and evaluate changes to landscapes and water resources. He has published multiple articles in prominent peer-reviewed, scientific journals. Konrad's code and workflow contribute to operational products that inform water and ecosystem management.

Latest Tutorials