- QGIS Python Programming Cookbook
- Joel Lawhead
- 318字
- 2021-07-23 19:48:57
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:
- Start QGIS.
- From the Plugins menu, select Python Console.
- First, load the layer and validate it:
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
- Next, define the feature IDs you want to change:
fid1 = 22 fid2 = 23
- 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")
- 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"}
- 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.
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第二版)
- Visual C++程序設(shè)計(jì)教程
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- Oracle Exadata性能優(yōu)化
- The Modern C++ Challenge
- 算法訓(xùn)練營:入門篇(全彩版)
- ASP.NET 3.5程序設(shè)計(jì)與項(xiàng)目實(shí)踐
- HTML5+CSS3網(wǎng)頁設(shè)計(jì)
- 快人一步:系統(tǒng)性能提高之道
- Python之光:Python編程入門與實(shí)戰(zhàn)
- 零基礎(chǔ)趣學(xué)C語言
- Mastering Python Design Patterns
- R語言:邁向大數(shù)據(jù)之路(加強(qiáng)版)
- 零基礎(chǔ)輕松學(xué)C++:青少年趣味編程(全彩版)
- Photoshop CC移動(dòng)UI設(shè)計(jì)案例教程(全彩慕課版·第2版)