Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Deleting a vector layer attribute


In this recipe, we'll wipe out an entire attribute and all the feature fields for a vector layer.

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...

This operation is straight forward. We'll load and validate the layer, use the layer's data provider to delete the attribute by index, and finally, we will update all the fields to remove the orphaned values. To do this, we need to perform the following steps:

  1. Start QGIS.

  2. From the Plugins menu, select Python Console.

  3. First, load and validate the layer:

    vectorLyr =  QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
    vectorLyr.isValid()
    
  4. Then, delete the first attribute:

    vectorLyr.dataProvider().deleteAttributes([1]) 
    
  5. Finally, update the fields:

    vectorLyr.updateFields()
    

How it works...

Because we are changing...