QGIS Python Programming Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

Changing a vector layer feature's attribute

Changing a feature's attribute is very straightforward, and well-supported by the PyQGIS API. In this recipe, we'll change a single attribute, but you can change as many attributes of a feature at once as desired.

Getting ready

You will need the New York City museums shapefile used in other recipes, which you can download as a ZIP file from the following URL:

https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip

Extract this shapefile to /qgis_data/nyc.

How to do it...

We will load the shapefile as a vector layer, validate it, define the feature ID whose fields we want to change, define the new attribute value as an attribute index and value, and change the feature in the layer:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. First, load the layer and validate it:
            vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp',
                                       'Museums' , "ogr") 
            vectorLyr.isValid() 
    
  4. Next, define the feature ID we want to change:
            feat_id = 22 
    
  5. Now, we'll create the Python dictionary for the attribute index and the new value, which, in this case, is an imaginary phone number:
            attr = {1:"(555) 555-5555"} 
    
  6. Now, we use the layer's data provider to update the fields:
            vectorLyr.dataProvider().changeAttributeValues({feat_id : attr}) 
    

How it works...

Changing attributes is very similar to changing the geometry within a feature. If you wanted to change more fields at once, you would just expand the Python dictionary with more keys and values.