4

I want to use the Python Console in QGIS to change all attributes in a Shapefile with a certain value. I have a field named "ANB" and I want to change the value "2" in for example "3".

I know how to access the layer and select the values I want:

layer=QgsVectorLayer("C:.../Briefkasten.shp","briefkasten","ogr")

selection=layer.getFeatures(QgsFeatureRequest().setFilterExpression(u' "ANB"=2'))

But I don't know how to proceed.

Can someone help me? Thank you very much!

Greetings Robert

Robert BK
  • 81
  • 1
  • 4
  • If I understand correctly, you want to change all the entries where "ANB"=2 to "ANB"=3. Is that right? And selection may contain more than one occurrence of "ANB"=2, yes? – Tom Barron Jan 05 '18 at 21:15
  • In case my guesses above are correct, I would think that your selection variable will have a list attribute containing the entries found by getFeatures(). You can see the attributes of selection by doing "dir(selection)" and then doing "select." to see an attribute's value. You need to find the one that has the list you're interested in. I hope this helps. I'm not familiar with QGIS, but I'm telling you in general how Python objects typically behave. – Tom Barron Jan 05 '18 at 22:00
  • Yes Tom, you understand it correctly. Thank you very much! I will post the code below in case someone has a similar problem. – Robert BK Jan 06 '18 at 09:23
  • Good job, Robert! You answered your own question. :) – Tom Barron Jan 07 '18 at 11:28

1 Answers1

4

With the help of Tom I figure out the correct code (comments in german, sorry for that)

#####Vektorlayer (Shape) in QGIS laden:

layer=QgsVectorLayer("C:/Users/robert 2/Documents/QGIS_Python/Briefkasten.shp","briefkasten","ogr")
QgsMapLayerRegistry.instance().addMapLayers([layer])


#####Attribut aus Shape abfragen

layer=QgsVectorLayer("C:/Users/.../QGIS_Python/Briefkasten.shp","briefkasten","ogr")
features=layer.getFeatures()
f=features.next()
f.attributes()

##Index von bestimmten Spaltennamen finden um den später ansprechen zu können (ANB beinhaltet dann Index als Zahl) 
ANB=f.fields().indexFromName('ANB')

## nur ein bestimmtes Attribut aus einer Spalte auswählen und anzeigen lassen
selection=layer.getFeatures(QgsFeatureRequest().setFilterExpression(u' "ANB"=2'))

## selektierte Werte updaten:

layer.startEditing()
for feat in selection:
  layer.changeAttributeValue(feat.id(), ANB, 3)

layer.commitChanges()
Robert BK
  • 81
  • 1
  • 4
  • the use of this method is described here: https://qgis.org/pyqgis/master/core/QgsVectorLayer.html?highlight=#qgis.core.QgsVectorLayer.changeAttributeValue – Comrade Che Jun 03 '19 at 05:12