TransWikia.com

Populating row numbers with Field calculator using PyQGIS

Geographic Information Systems Asked by hmnoidk on July 4, 2021

I have the following code, which is creating a new column called "group" without issue, but not populating it with a row number 1-n, as I’m intending it to.

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

layer.updateFields()
expression = QgsExpression('@row_number')

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

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

I do not get an error, it just prints a bunch of null values instead of 1-n.

enter image description here

Is anything popping out as wrong? I followed a tutorial verbatim, and just substituted @area for @row_number, which is the expression I need in this case.
I replaced @row_number with $id and it worked, but I’d still like to know why @row_number doesn’t.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP