- QGIS Python Programming Cookbook
- Joel Lawhead
- 306字
- 2021-07-23 19:48:56
Adding a field to a vector layer
This recipe demonstrates how to add a new field to a layer. Each field represents a new column in a dataset for which each feature has a new attribute. When you add a new attribute, all the features are set to NULL
for that field index.
Getting ready
We will use 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...
All the data management for a layer is handled through the layer's data provider and the fields are no different. We will load the layer, access the data provider, define the new field, and finalize the change, as follows:
- Start QGIS.
- From the Plugins menu, select Python Console.
- First, you must import the
Qt
library's data types, which PyQGIS uses to specify the layer field's data types:from PyQt4.QtCore import QVariant
- Next, load and validate the layer:
vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
- Then, access the layer data provider:
vpr = vectorLyr.dataProvider()
- Now, add a Python list of
QgsField
objects, which defines the field name and type. In this case, we'll add one field namedAdmission
as aDouble
:vpr.addAttributes([QgsField("Admission", QVariant.Double)])
- Finally, update the fields to complete the change:
vectorLyr.updateFields()
How it works...
The nomenclature used for the fields
and attributes
in QGIS is a little inconsistent and can be confusing if you've used other GIS packages. In QGIS, a column is a field
that has a name and a type. The attribute table
holds a value for each field
column and each feature
row. However, in the QgsVectorDataProvider
object, you use the addAttributes()
method to add a new field
column. Also, in other GIS software, you may see the use of the word field
and attribute
reversed.
- Learning Microsoft Windows Server 2012 Dynamic Access Control
- Git Version Control Cookbook
- 控糖控脂健康餐
- Flask Web開發入門、進階與實戰
- Android 9 Development Cookbook(Third Edition)
- Python進階編程:編寫更高效、優雅的Python代碼
- Learning Informatica PowerCenter 10.x(Second Edition)
- Java項目實戰精編
- Microsoft Azure Storage Essentials
- 開源項目成功之道
- MySQL程序員面試筆試寶典
- Mastering VMware Horizon 7(Second Edition)
- 數據科學中的實用統計學(第2版)
- 基于GPU加速的計算機視覺編程:使用OpenCV和CUDA實時處理復雜圖像數據
- 嵌入式C編程實戰