I want to calculate new values with the QGIS field calculator, while running the code in the calculator GUI from QGIS it works quite well, but trying to apply this via PyQGIS it just give me in expression_2cl the value after the else statement "Hardwood".

What is wrong with my syntax that QGIS doesn't recognize the full statement?

#Create new fields
pv = layer.dataProvider()
QgsField('2_classes', QVariant.String)])


expression_SW = QgsExpression('("basalareap"+"basalareas")/("basalareap"+"basalareas"+"basalaread")')
expression_2cl = QgsExpression('CASE WHEN \"Share_SW\" >= 0.5 THEN \'Softwood\' ELSE \'Hardwood\' END')

context = QgsExpressionContext()

System Windows 10 QGIS 3.10

  • I don't have much practice with pyqgis, so forgive my ignorance. I don't see where you are calculating the 'Share_HW'. I see you create the field, but I don't see anything going into it. Is this happening further on in the code and isn't shown here? If there is no value in 'Share_HW' your case statement will always return 'Hardwood'.
    – jbalk
    Jan 27 '20 at 23:55
  • you could also wrap the case statement in triple quotes (""") to remove the need to escape the rest of the quotes
    – jbalk
    Jan 27 '20 at 23:57
  • I updated my code. Two expressions where not of interest for the question.
    – DrSnuggles
    Jan 28 '20 at 13:28
  • @jbalk thank you for the tip, but this doesn't change anything on the output.
    – DrSnuggles
    Jan 28 '20 at 13:37
  • 1
    Well, your syntax is correct so I'm not sure what the problem is. You haven't provided any of your code showing where you're calculating 'Share_HW'. I can see the expression you're creating to calculate share_hw, but you don't show where/how you're using the expression. Like I said in my first comment, if that calculation is not happening, all you're going to get from your case statement is 'Hardwood'.
    – jbalk
    Jan 28 '20 at 19:36

Your Answer

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

Browse other questions tagged or ask your own question.