官术网_书友最值得收藏!

Changing a vector layer feature's attribute

The process to change an attribute in a feature is 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 as desired at once.

Getting ready

You will need the New York City museums' shapefile used in other recipes, which you can download as a ZIP file from https://geospatialpython.googlecode.com/svn/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 IDs of the fields we want to change, get the index of the field names that we will change, define the new attribute value as an attribute index and value, and change the feature in the layer. To do this, we need to perform the following steps:

  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 IDs you want to change:
    fid1 = 22
    fid2 = 23
    
  5. Then, get the index of the fields you want to change, which are the telephone number and city name:
    tel = vectorLyr.fieldNameIndex("TEL")
    city = vectorLyr.fieldNameIndex("CITY")
    
  6. Now, create the Python dictionary for the attribute index and the new value, which in this case is an imaginary phone number:
    attr1 = {tel:"(555) 555-1111", city:"NYC"}
    attr2 = {tel:"(555) 555-2222", city:"NYC"}
    
  7. Finally, use the layer's data provider to update the fields:
    vectorLyr.dataProvider().changeAttributeValues({fid1:attr1, fid2:attr2})
    

How it works...

Changing attributes is very similar to changing the geometry within a feature. We explicitly name the feature IDs in this example, but in a real-world program, you would collect these IDs as a part of some other process output, such as a spatial selection. An example of this type of spatial selection is available in the Filtering a layer by Geometry recipe, in Chapter 2, Querying Vector Data.

主站蜘蛛池模板: 尚志市| 泌阳县| 盖州市| 延川县| 汉阴县| 德保县| 彩票| 呼玛县| 洛扎县| 通州区| 衡东县| 武平县| 明星| 荣成市| 丹阳市| 崇左市| 吉林市| 呼和浩特市| 白水县| 奉贤区| 吴堡县| 河北省| 钟山县| 津南区| 广东省| 桃园市| 长顺县| 博野县| 武功县| 城步| 鞍山市| 疏附县| 民县| 万盛区| 顺平县| 湘潭县| 祥云县| 遂宁市| 汝州市| 临夏县| 白城市|