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

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:

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. 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
    
  4. Next, load and validate the layer:
    vectorLyr = QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
    vectorLyr.isValid()
    
  5. Then, access the layer data provider:
    vpr = vectorLyr.dataProvider()
    
  6. Now, add a Python list of QgsField objects, which defines the field name and type. In this case, we'll add one field named Admission as a Double:
    vpr.addAttributes([QgsField("Admission", QVariant.Double)])
    
  7. 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.

主站蜘蛛池模板: 惠东县| 通渭县| 洪江市| 岗巴县| 渑池县| 迁西县| 三穗县| 扬中市| 门源| 福贡县| 平潭县| 外汇| 阳信县| 永和县| 清远市| 萍乡市| 黔西| 蓬安县| 永靖县| 班玛县| 准格尔旗| 丹巴县| 稷山县| 恩平市| 凤翔县| 固安县| 郓城县| 监利县| 六盘水市| 岳普湖县| 新巴尔虎左旗| 大冶市| 舞阳县| 常山县| 金沙县| 武隆县| 洛阳市| 娱乐| 新泰市| 阳曲县| 株洲市|