7

I have some data from the field survey. In the field, I write down integers that I want to expand afterward. What I do is using the field calculator and something like:

CASE
WHEN A is 1 THEN 'foo'
WHEN A is 2 THEN 'bar' 
ELSE A
END

I have a lot of attribute fields that I have to process and it is a pain doing it this way. Is there a possibility of achieving this in batch?

2 Answers 2

10

You can use "Refactor Fields" tool.

  • Specify field Type as Text for the fields you need to change.

enter image description here

  • Copy the expression to the fields and change the field names in the expression. (I recommend using expression window or a text editor (Notepad) to edit the expression. Because when you edit a character, the cursor goes to the end of the line, unexpectedly)

enter image description here

10

You can use pyqgis with a dictionary:

Change first four lines:

lyr = QgsProject.instance().mapLayersByName('ok_ak_riks')[0]
sourcefield = 'A'
destfield = 'abcd'
remap = {1:'foo', 2:'bar'}
        
idxdest = lyr.fields().indexFromName(destfield)
idxsource = lyr.fields().indexFromName(sourcefield)
attrmap = {}

for f in lyr.getFeatures():
    if f[sourcefield] in remap:
        attrmap[f.id()] = {idxdest:remap[f[sourcefield]]}
    else:
        attrmap[f.id()] = {idxdest:f[sourcefield]}

lyr.dataProvider().changeAttributeValues(attrmap)

enter image description here

Your Answer

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

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