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
Taras
  • 32,823
  • 4
  • 66
  • 137
Chris Papas
  • 717
  • 2
  • 9
  • 20
  • 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 http://docs.qgis.org/2.14/de/docs/pyqgis_developer_cookbook/vector.html#modify-features – Jochen Schwarze May 03 '17 at 05:28

1 Answers1

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".

Taras
  • 32,823
  • 4
  • 66
  • 137
artwork21
  • 35,114
  • 8
  • 66
  • 134