I am looking for solution to get the unique values of an attribute of a vector layer.
What is the best way in PyQGIS to get the unique values of one distinct attribute?
I have polygons described by an attribute "group". Each group contains 1 to about 10 polygons. I want to process the polygons belonging to a certain group in for-loop, i.e. for each iteration of the for-loop i select the polygons with setSubsetString
to process this group, e.g. to write them to a shape file. However I do not know the group before reading the vector layer.
I work with QGIS 1.8.0.
-
2There is a split tool which will create separate shapefiles depending on an attribute if that's all you need. Otherwise, that plugin would also be the place to look for sample code.underdark– underdark2013年10月08日 18:58:18 +00:00Commented Oct 8, 2013 at 18:58
-
From the plugin you were mentioned the function split in splitterdialog.py is what i was looking for. Thank you for the hint!gallay– gallay2013年10月08日 20:04:23 +00:00Commented Oct 8, 2013 at 20:04
3 Answers 3
QGIS provides a method .uniqueValues(fieldIndex)
of the QgsVectorLayer
class to get this information. You need to get the index of the field in question and then query the layer for unique values.
vectorLayer = iface.activeLayer()
idx = vectorLayer.fields().indexOf('FIELD_NAME')
values = vectorLayer.uniqueValues(idx)
Python's sets are handy for finding unique values. For example:
>>> set(range(4) + range(5) + range(6))
set([0, 1, 2, 3, 4, 5])
Try something like this:
PyQGIS 2.0:
values = set()
for feature in layer.getFeatures():
values.add(feature[ATTRNAME])
PyQGIS 1.8:
values = set()
layer.select()
for feature in layer:
index = layer.fieldNameIndex(ATTRNAME)
values.add(feature.attributeMap()[index].toInt())
There is a QGIS algorithm for that called "List unique values"
layer = iface.activeLayer()
params = {
'INPUT' : layer,
'FIELDS' : ['FIELD_NAME'],
'OUTPUT' : 'TEMPORARY_OUTPUT',
'OUTPUT_HTML_FILE' : 'TEMPORARY_OUTPUT'
}
result = processing.run("qgis:listuniquevalues", params)
print(result['UNIQUE_VALUES'])
-
Dear @saheka, I decided to rollback your answer, because I noticed, that your initial version was unique (the last edit version overlapped too much with MatthiasKuhn's answer) and it is still usable.2025年06月20日 07:44:10 +00:00Commented Jun 20 at 7:44
Explore related questions
See similar questions with these tags.