1

I want to add a row number in QGIS 3 using Python.

First of all I add a new field with the code below and it works.

Then I want to fill the table with the row number. In QGIS Field Calculator there is the function @row_number. That is exactly what I want. But I want to do it automatically with Python. The code below doesn't work.

## join ID field
vlayer=##
myField1 = QgsField('ID', QVariant.Double)
vlayer.startEditing()
vlayer.dataProvider().addAttributes([myField1])
vlayer.updateFields()
idx=vlayer.dataProvider().fieldNameIndex('ID')
e = QgsExpression('$rownum')

##fill the attributes with ID-Number
for f in vlayer.getFeatures():
    f[idx]=e
    vlayer.updateFeature(f)

vlayer.commitChanges()

Is there an easy way to add a row number or an ID with Python?

0

Create a count variable:

field_to_update = 'int_id' #Change
layer = iface.activeLayer()
field_index = layer.dataProvider().fieldNameIndex(field_to_update)
layer.startEditing()
count=1
for feature in layer.getFeatures():
    _=layer.changeAttributeValue(feature.id(),field_index,count)
    count+=1
layer.commitChanges()
  • Thanks for your advice. Unfortunately it doesn't work the way you suggested, but led me to the right track. I will post the new code below. – Helga F. Jan 28 at 10:44
0

I used the input I got and modified it. The new code is:

## vlayer=iface.activeLayer()    

## join ID field
myField1 = QgsField('ID', QVariant.Double)
vlayer.startEditing()
vlayer.dataProvider().addAttributes([myField1])
vlayer.updateFields()
ID=vlayer.dataProvider().fieldNameIndex('ID')
vlayer.commitChanges()

count=1
vlayer.startEditing()
# fill the field ID with rownumber
for f in vlayer.getFeatures():
    attr_ID=f.attributes()[ID]
    rownum = count
    count+=1
    f[ID]=rownum
    vlayer.updateFeature(f)

vlayer.commitChanges()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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