[GIS] Syntax of conditional statements in QGIS Field Calculator(s)

field-calculatorqgisqgis-modeler

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…

Best Answer

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.

Related Question