If I have a vector layer in QGIS, how do I use Python to find the maximum value which a given field has? I need to convert the values in one field into values between 0 and 1. I guess I therefore need to set it to val/maxVal. That's why I need to find the maximum value.

  • and what if I'd like to evaluate the maximum for each unique value? This doesn't work at all...could someone find the error? thanks uniquevalues=layer.uniqueValues(index,limit=10000) for uv in uniquevalues: features = layer.getFeatures() for feat in features: values = [] attrs = feat.attributes() values.append(attrs[field]) if feat[field] == uv: maxarea = max(values) – FedericaZ May 17 '17 at 15:44

It is not necessary to get a complete list of field values. In QgsVectorLayer exists 'maximumValue' method. So, this works well and it's shorter:

layer = iface.activeLayer()

idx = layer.fieldNameIndex('fieldName')
print layer.maximumValue(idx)
  • 1
    I really should read the API more often ;) – Joseph Sep 15 '16 at 12:04
  • Perfect - just what I needed, and works perfectly. Thanks! – Tom Chadwin Sep 15 '16 at 12:46
  • 2
    Just a note - the biggest advantage of using QgsVectorLayer.maximumValue over iterating through every value is that maximumValue can hand calculation of the maximum over to the data source itself. Ie, for a Postgres layer QGIS will send a simple "select max("field") from ..." query to the database, rather then having to fetch every single feature from the database and iterate through them. It's a dramatic performance win. – ndawson Sep 15 '16 at 22:07
  • Not working on string columns. Code proposed by Joseph fix te issue. – Kostadin Jan 16 '18 at 14:07

You could use the following in the Python Console to print out the maximum value for a given field:

values = []
layer = qgis.utils.iface.activeLayer()
idx = layer.fieldNameIndex('fieldName')
for feat in layer.getFeatures():
    attrs = feat.attributes()

print max(values)
  • 1
    It is not necessary to get a complete list of field values. In QgsVectorLayer exists 'maximumValue' method. – xunilk Sep 15 '16 at 12:02
  • 1
    Also works, but @xunilk's is the better solution. – Tom Chadwin Sep 15 '16 at 12:47
  • @TomChadwin - Can't argue there =) – Joseph Sep 15 '16 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.