i look for solution to get the unique values of an attribute of a vector layer. what is the best way in python qgis to get the unique values of one distinct attribute? I work with qgis 1.8.0.
-
In QGIS without python you could just query the FieldCalculator with all unique values of a field (there is a button on the right side). A pythonic solution would also be possible. What do you need this value for? Please elaborate a bit– CurlewCommented Oct 8, 2013 at 17:42
-
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 befor reading the vector layer.– gallayCommented Oct 8, 2013 at 18:30
-
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.– underdarkCommented 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!– gallayCommented Oct 8, 2013 at 20:04
3 Answers
QGIS provides a simple API to get this information. You need to get the index of the field in question and then query the layer for unique values.
idx = vectorLayer.fields().indexOf('fieldName')
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 1.8):
values = set()
layer.select()
for feature in layer:
index = layer.fieldNameIndex(ATTRNAME)
values.add(feature.attributeMap()[index].toInt())
Pyqgis 2.0:
values = set()
for feature in layer.getFeatures():
values.add(feature[ATTRNAME])
Late but maybe somebody can use it.
It is also posible to use the native python function. The uniqueValues function of the child for vector layers of the class QgsDataProvider.
See the Qgis API: QgsDataProvider and QgsVectorDataProvider
uniquevalues = []; uniqueprovider = layer.dataProvider() fields = uniqueprovider.fields() id = fields.indexFromName('nameOfField') uniquevalues = uniqueprovider.uniqueValues( id ) for uv in uniquevalues: print uv
i do that from qgis phyton console.
-
1Answer has been flagged as low quality. Could use a little more context and explanation - where would you enter this command, what and where does it output (a table?), etc.– Chris WCommented Jul 17, 2015 at 23:38
-
1
-