Let's imagine to have a vector layer whose attribute table is made of an ID field, a field "A" (string) and a field "B" (float).

I am trying to access a specific feature (e.g. [0]) in field A, comparing the selected value with the one after([1]) in the same column and, based on this, doing something.

If I were working on a spreadsheet, I'd write: IF(A0=A1; B0=x;""). Based on the final hint enclosed in a previous discussion (link), which is quite closed, I tried to use it but:

  • it moves among fields (horizontally) and not features (vertically)

  • and I should activate it for each feature (but what about if there are many features?)


features = layer.getFeatures()
attrs = feat.attributes()
attr = attrs[0]
Index=2 # field index
request = QgsFeatureRequest().setFilterFid(0) 
#feature index
feat = layer.getFeatures(request).next()
print feat.attributes()[Index] 
#thus, the result returned is the first feature in third field
#I change the index to the 1st.one on the right
print feat.attributes()[Index] 
#thus, I obtain the 1st feature of the 4th field
  • Please format your code with the {} button. If you take the Tour you'll see that paragraphs with greetings and thanks are considered distractions from the problem statement.
    – Vince
    Apr 13 '17 at 11:56
  • How many rows do you have in your layer?
    – mgri
    Apr 13 '17 at 12:08
  • @mgri Number of rows: thousands...
    – FedericaZ
    Apr 13 '17 at 12:25

Thanks to Oscar Campolmi who helped me, a possible script could be:

listLayers = QgsMapLayerRegistry.instance().mapLayers().values() 
    for layer in listLayers:
            field_index_nome = layer.dataProvider().fieldNameIndex('Name')
            field_index_numero =layer.dataProvider().fieldNameIndex('Number')
            field_index_somma = layer.dataProvider().fieldNameIndex('Sum')

            unique_values = layer.uniqueValues(field_index_nome, limit=1001)

            for val in unique_values:
                count = 0
                features = layer.getFeatures()
                for f in features:
                    if f[field_index_name] == val:
                        number = f[field_index_numero]
                        count = count + number
                        layer.changeAttributeValue(f.id(), field_index_somma, count)


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.