Deleting a vector layer feature's attribute
In this recipe, we'll remove an entire attribute and all feature fields for a vector layer. Remember, attributes are the column names and fields are the inpidual values.
Getting ready
You will need the New York City museums shapefile used in other recipes, which you can download as a ZIP file from the following URL:
https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip
Extract this shapefile to /qgis_data/nyc
.
How to do it...
This operation is straightforward. We'll load and validate the layer, use the layer data provider to delete the attribute by index, and finally update all of the fields to remove the orphaned values:
- Start QGIS.
- From the Plugins menu, select Python Console.
- First, we load and validate the layer:
vectorLyr= QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr") vectorLyr.isValid()
- Then, we delete the first attribute:
vectorLyr.dataProvider().deleteAttributes([1])
- Finally, we update the fields:
vectorLyr.updateFields()
How it works...
Because we are changing the actual structure of the layer data, we must call the updateFields()
method of the layer to remove the field values, which no longer have an attribute. We have changed the underlying structure of the data and must notify QGIS.