12

I have a shapefile which I need to modify. There is one column "CLASS" with the attributes: "A", "B" and "C". I need to change "A" into "1", "B" into "2" and "C" into "3". I tried it with case when function. With one case it's not a problem but how does it work with 3 in row?

Is it also possible to build a model with the FieldCalculator function?


I guess I figured it out! Is this right?

CASE
  WHEN "VSt_K" IS 'E' THEN '5'
  WHEN "VSt_K" IS 'A' THEN '1'
  WHEN "VSt_K" IS 'B' THEN '2'
  WHEN "VSt_K" IS 'C' THEN '3'
END

But I can't use this in the modeler FieldCalculator function...

14

If you are calculating a field of String type, this is the right syntax:

CASE 
  WHEN "VSt_K" = 'A' THEN '1'
  WHEN "VSt_K" = 'B' THEN '2'
  WHEN "VSt_K" = 'C' THEN '3'
END

Instead, if it's of Integer type:

CASE 
  WHEN "VSt_K" = 'A' THEN 1
  WHEN "VSt_K" = 'B' THEN 2
  WHEN "VSt_K" = 'C' THEN 3
END

EDIT

The syntax of the Advanced Python Field Calculator in Processing Toolbox is different from that of the standard QGIS Field calculator. So you should write your conditional expressions using Python:

Global expression:

def getValue(x):
    if x == 'A':
        value = '1'
    elif x == 'B':
        value = '2'
    elif x == 'C':
        value = '3'
    # ...and so on
    return value

Formula:

value = getValue( <VSt_K> )

Note: it's possible to use the Advanced Python Field Calculator in Modeler, however you have to specify the source field(s) directly in its formula, because fields cannot be used as input parameters when using this algorithm. Alternatively, you can define an input String parameter containing the default formula. When you run the model, you can eventually change the source field(s) in the Formula input parameter, thus making the model perfectly reusable with other data.

  • Thank you, it works! But do you also know how I could use the field calculator (with the shown syntax)in the modeler? – Pimpel Jan 31 '14 at 9:33
  • I've added further details in the answer, explaining how to do it. Hope this helps. – Antonio Falciano Jan 31 '14 at 11:15
  • Thank you! I tried but there is one little problem. Now the result is that I just got the "C" changed into "3". When I added the 'elif x == 'D':value = '4' string I only get the "D" changed into "4". – Pimpel Jan 31 '14 at 12:50
  • If you calculate a new field from scratch, it should work as expected. – Antonio Falciano Jan 31 '14 at 15:33
  • I dont know why but when Im running my model now (didnt change anything) it says: ...return value, FORMULA =value = getValue( ) Failed Error executing algorithm 0 local variable 'value' referenced before assignment See log for more details – Pimpel Jan 31 '14 at 20:20

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.