2

I have a shapefile and I want to select some features and update specific field with PyQGIS.

for example :

myshape:
myfield(values)
1
2
3
4
5
6
7
8

This is my pseudocode:

newvalue = 1212

for feature in selected:
    i = feature[myfield]     
    feature[myfield] = i + newvalue

where i is order number to avoid duplicate.

Resulting in something like (provided 5...8 were selected):

myshape:
myfield(values)
1
2
3
4
1217
1218
1219
1220
1
  • 2
    Everything is possible with a bit of python. But adding a certain value to an integer attribute sounds not like a good idea to avoid duplicate values. If you simply want id's to your features, consider 'update existing fields' in field calculator and use the $id function, which will generate unique id's. Otherwise I suggest looking at the PyQGIS Developer Cookbook, Working with vector layers, modifying vector layers docs.qgis.org/2.14/de/docs/pyqgis_developer_cookbook/… May 3, 2017 at 5:28

1 Answer 1

4

The logic flow you may follow for this is:

  1. Create a QgsVectorLayer
  2. Start edit session on layer
  3. Get index of field you want to update using layer.fieldNameIndex('myFieldName')
  4. Get layer features and loop through feature values
  5. Use if conditional logic to evaluate what the current value is and decide if it will be updated or not
  6. If update then use layer.changeAttributeValue(feature.id(), index, value + feature['myFieldName']) # assuming both value and field are type integer
  7. Finally, commit edits using layer.commitChanges()

You'll find many examples of each of these steps on the web with a key word search like "pyqgis qgs vector layer" or "pyqgis start edit session on vector layer".

2
  • can you show me a complete example ?I am very new in club May 5, 2017 at 21:58
  • AttributeError: 'QgsVectorLayer' object has no attribute 'fieldNameIndex', v3.14. See why.
    – mins
    Feb 18, 2022 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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