How to select features in QGIS using Python

In this task we will load a vector layer representing some data about population and use python scripting to select all the cities with more than one million people.

We will use a dataset from Natural Earth: download the population shapefile here.

population

The data about city population are contained in the attribute “pop_max”, as you can see if you select the Identify tool and click on any of the points to examine the available attributes:

identify

Method 1

Use this method if your layer is not already loaded in QGIS. Otherwise, directly skip to Method 2.

from qgis.core import *

# Load the layer
layer = QgsVectorLayer('C:/Users/.../ne_10m_populated_places_simple.shp',
'Population', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(layer)

# Write the filter expression and set it
query = '"pop_max" > 1000000'
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.setSelectedFeatures([k.id() for k in selection])

Method 2

Use this method if your layers are already loaded in the Layers Panel in QGIS.

##Population=vector

from qgis.core import *
import processing
# Load the layer
layer = processing.getObject(Population)

# Write the filter expression and set it
query = '"pop_max" > 1000000'
selection = layer.getFeatures(QgsFeatureRequest().setFilterExpression(query))
layer.setSelectedFeatures([k.id() for k in selection])

Regardless of the method used, this will be the result:

query

You can save this selection by right clicking on the name “Population” in the Layers Panel and then by checking the box “Save only selected features”.

 

Advertisements

One thought on “How to select features in QGIS using Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s