1

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

for example :

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

I want to select some features and update automate something like this (pseudocode):

newvalue = 1212

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

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
    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/… – Jochen Schwarze May 3 '17 at 5:28
2

The logic flow you may follow for this is:

  1. Create Qgs vector layer
  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"...

  • can you show me a complete example ?I am very new in club – Chris Papas May 5 '17 at 21:58

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.