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?