Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mdouchin/a234efb7e67ebd8dae3a04cb26cf5e72 to your computer and use it in GitHub Desktop.
Save mdouchin/a234efb7e67ebd8dae3a04cb26cf5e72 to your computer and use it in GitHub Desktop.
# QGIS 3 (compatible with 2.18) python code to count features
# for each unique value of chosen fields
#
# Copy paste in your python console
# You need to change the "fields" variable below
# And select the layer in QGIS legend before running it
#
# The output memory layer attribute table would be like
# fieldname fieldvalue count
# menace EN 19355
# menace LC 129845
# menace NA 15068
# menace 122127
# categorie Gymnospermes 248
# categorie Vers 1
# categorie Poissons 649
# categorie Autres 7
# categorie Angiospermes 212331
# categorie Arachnides 2
layer = iface.activeLayer()
# List of field names from which to gather stats
fields = ('categorie', 'menace')
# import needed classes
from qgis.core import QgsVectorLayer, QgsFeature, QgsField, QgsFeatureRequest
try:
# QGIS 3
from PyQt5.QtCore import QVariant
except:
# QGIS 2
from PyQt4.QtCore import QVariant
# Create dictionnary with the list of unique values for each field
c = dict([(f,{}) for f in fields])
for k in c.keys():
try:
# QGIS 3
idx = layer.fields().indexFromName(k)
except:
# QGIS 2
idx = layer.fieldNameIndex(k)
c[k] = dict([(a,0) for a in layer.uniqueValues(idx)])
# Loop through the active layer
# And sum up counters from feature
# it is very important to set the NoGeometry flag
# and add the subset of interesting fields
# to improve performance
request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry).setSubsetOfAttributes(fields, layer.fields() )
for feat in layer.getFeatures(request):
for k in c.keys():
a = feat[k]
c[k][a]+= 1
# create memory layer to store data
vl = QgsVectorLayer(
"None",
"fields_unique_values_count",
"memory"
)
pr = vl.dataProvider()
pr.addAttributes([
QgsField("fieldname", QVariant.String),
QgsField("fieldvalue", QVariant.String),
QgsField("count", QVariant.String)
])
vl.updateFields()
# Add layer to QGIS canvas
try:
# QGIS 3
QgsProject.instance().addMapLayer(vl)
except:
# QGIS 2
QgsMapLayerRegistry.instance().addMapLayer(vl)
# add features to the memory layer
for k,v in c.items():
for i,j in v.items():
#print(k,i,j)
fet = QgsFeature()
fet.setAttributes([k, i, j])
pr.addFeatures([fet])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment