In QGIS I want to search for a specific case and if this is true then replace the text in multiple columns. Based on Use updatcursor to replace values in multiple fields, Update multiple fields/columns in QGIS and Elseif Conditional Statement in QGIS Field Calculator
I have
# definition of the function which calculates new values
def upd_value(sfield, svalue, outvalue):
# criteria
if search<>svalue:
outvalue=svalue
return outvalue
# get the active layer
layer = iface.activeLayer()
prov = layer.dataProvider()
# get the fields
fnm = prov.fieldNameMap()
# get an iterator for the features
feats = prov.getFeatures()
# calculate new values and update fields with fieldnames
I am not sure how to end this. Basically I need the following
When
lower("Given_name")<>lower( "z_Given Names") and 'Surname' is not Null
Then
"Given_Name" field should be filled with "z_Given_Names"
"Surname" field should be filled with "z_Surname"
(lots of other fields which I can add in once I know what to do)
"Status" with 'Updated fields from z table as names not same'
When
"Status" = 'V' and "Surname" is Null
Then
"Given_Name" field should be filled with "z_Given_Names"
"Surname" field should be filled with "z_Surname"
"Status" with 'New'
Answer
You could perhaps use something like the following which focuses on your first When
statement. Essentially, after you define the fields and expressions for searching and applying values, the script finds all features based on your search expression (e.g. lower("Given_name")<>lower( "z_Given Names") and 'Surname' is not Null
) and applies the expression for the values for each specified field:
layer = qgis.utils.iface.activeLayer()
# Set field names you want to update
field_1 = "Given"
field_2 = "Surname"
idx_1 = layer.fieldNameIndex( field_1 )
idx_2 = layer.fieldNameIndex( field_2 )
# Set expression to find all features which fall into expression
exp = QgsExpression( """ lower("Given_name")<>lower( "z_Given Names") and 'Surname' is not Null """ )
# Select all features which fall into expression
ids = [i.id() for i in layer.getFeatures(QgsFeatureRequest(exp))]
layer.setSelectedFeatures(ids)
# Set expressions to fill in values for selected features
formula_1 = """ "z_Given_Names" """
formula_2 = """ "z_Surname" """
e_1 = QgsExpression(formula_1)
e_2 = QgsExpression(formula_2)
with edit(layer):
# For each selected feature
for f in layer.selectedFeatures():
f[idx_1] = e_1.evaluate(f)
f[idx_2] = e_2.evaluate(f)
layer.updateFeature(f)
Tested in the Python Console for QGIS 2.12.3-Lyon.
No comments:
Post a Comment