Using lookup from CSV in Field Calculator?
You could make use of the Function editor in the Field Calculator which allows you to create a function. This can return the value from the COST
column when specifying the ITEM
.
In your Field Calculator, click the Function Editor tab, either create a new file or edit an existing one and enter the following code:
from qgis.core import * from qgis.gui import * import csv @qgsfunction(args='auto', group='Custom') def func(value, feature, parent): with open('path/to/csv') as f: reader = csv.reader(f) for row in reader: if row[0] == value: return row[1]
Then click Load.
Click the Expression tab and either create or update a field. If we type the expression:
func('FOOT')
It will return a value of 100 as written in your csv file. So for your first example, you can use the following expression to divide the
FOOT
value by the length of each line feature:func('FOOT') / $length
- Replace
func('FOOT')
withfunc('THING')
to return the 200 value which you can then use for other calculations.
(reviving this coming from a more recent linked Q)
The custom function approach is an effective one, but can be hard to read or maintain if you're not a python wizard. Also, custom functions need to reside in a file in your user profile and so are not automatically portable with the project.
Therefore you could also proceed as follows:
Load the CSV lookup file into your project as a Delimited text layer with no geometry.
Look up in field calculator using
attribute(get_feature(csvLayer,'Item','FOOT'),'COST')
(note single not double quotes - these are strings passed to the function, not attributes of the current feature in the current layer)Alternately, for slightly different use cases, you could join the CSV layer to the target layer by a shared field, e.g. to have access to the COST as a joined attribute if your layer had for each feature a single item type whose cost is the one you want to us.