I often have to rework a lot of columns in attribute tables (expand abbreviations, replace numerical values with string values, and so on).
Is there a way to do this more efficient than opening the field calculator and paste the CASE WHEN THEN END
statements into it for every single field that I want to rework? The field names of my tables are always the same.
Even a way with Python would be acceptable but I am not very familiar with pyqgis.
EDIT:
from PyQt5.QtCore import QVariant
from qgis.core import QgsField, QgsExpression, QgsFeature
lyr_path = r'/home/ktw/Schreibtisch/_testBumbleBee_QGIS/shp/bumblebees.shp'
#vl = QgsVectorLayer(lyr_path, "Hummeln", "ogr")
vl = iface.addVectorLayer(lyr_path, "Hummeln", "ogr")
expr_1 = QgsExpression('species')
context = QgsExpressionContext()
context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(vl))
pr = vl.dataProvider()
pr.addAttributes([QgsField('species2', QVariant.String)])
vl.updateFields()
with edit(vl):
for f in vl.getFeatures():
context.setFeature(f)
f['species2'] = expr_1.evaluate(context)
vl.updateFeature(f)
vl.commitChanges
This is what I got so far. It does nothing more than copying the values from species
to species2
.
I am struggling with QgsExpression()
.
I want to pass my SQL expression:
CASE
WHEN species IS 'B.ter' THEN 'Bombus terrestris'
WHEN species IS 'B.lap' THEN 'Bombus lapidarius'
WHEN species IS 'B.cry' THEN 'Bombus cryptarum'
WHEN species IS 'B.ves' THEN 'Bombus vestalis'
ELSE 'ERROR'
END
aggregate
, this allows you to do many things in addition to aggregating; in fact, if in the group field you put a field of the attribute table with unique values, it does not aggregate anything, but executes the expressions listed below. - link: docs.qgis.org/3.22/en/docs/user_manual/processing_algs/qgis/…