4

I've got two additional columns that need to be filled with attributes that are based on values created in the field.

For example, if column "reproduction" = A2 then the value in the value in column "technic" needs to be "acoustic" and the value in column "class" needs to be "adm" and so on.

I know how to update single fields by using case when but I could not find a solution for updating more than one field with one expression.

2 Answers 2

5

In Processing Toolbox (Ctrl+Alt+T) one can find the "Refactor fields" algorithm.

You can add new columns or change the value of the existing ones. In the plugin, the registry installs "Append Features to Layer". With both processing algorithms, you can accomplish what you want.

5

You can use the following code which is very easy to understand. Select the layer, first. You can populate with other logical conditions.

# get the selected layer
layer = iface.activeLayer()

with edit(layer): # open edti sessio for the layer

    for feature in layer.getFeatures():

        # condition 1
        if feature['reproduction'] == 'A2':
            feature['technic'] = 'acoustic'
            feature['class'] = 'adm'

        # condition 2
        elif feature['reproduction'] == 'foo':
            feature['technic'] = 'bar'
            feature['class'] = 'baz'

        # condition 3
        # elif featu.....

        # update feature values
        layer.updateFeature(feature)
4
  • So, what does f[]do? Why do I need to call iface.? Why is the last line necessary?
    – Erik
    Mar 25 at 9:46
  • x[y] = z assigns z to key y for the dictionary x. iface is the QGIS interface, iface.activeLayer() is a method that returns the currently active layer from the QGIS interface. Spend some time learning fundamental Python syntax and programming, and then move on to PyQGIS specifically if you're interested. Mar 26 at 3:03
  • thanks! I used the script also to update species names and encountered always a syntax error when doing it for the abr: 'Coloen' , which is Columba oenas. Could this result out of the first 3 strings "Col" `? Mar 26 at 14:47
  • I couldn't understand why the error was arisen. Did you try to use full name? feature['Columba oenas']. Mar 26 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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