I believe its pretty easy to be done, but I just don't seem to see the solution in Qgis. Is it possible in the field calculator?

I've an attributetable with 200 features with like 20 different soil_unit_code category's (aVz, EZ50A, Ezg21, etc). Just a string.

Now I want to give each soil_unit_code a number_id (1, 2, 3) in the new column: soil_id

In python it would look something like:

for i in soil_unit_code:
 soil_id = n
 n += 1

how would you do this with the Qgis field calculator? I'm not looking for the @row_number. That would give each feature an ID.

1 Answer 1


Use this expression:

array_find (array_distinct (array_agg("soil_unit_code")), "soil_unit_code")


With array_agg (array aggregate), you get a list (array) of all values from the field soil_unit_code. array_distinct filters this to unique values. With array_find, you look for the position inside this array of unique values that the current value of the field soil_unit_code has: this is the output-value, used here as code.

enter image description here

  • If you find the time, @Babel, could you also explain what the different parts of the expression do? I find this very helpful usually, since it expands my knowledge of the field calculator, and especially arrays are rather tricky to work with.
    – Erik
    Dec 3, 2021 at 12:19
  • 1
    @Erik - added that to my solution.
    – Babel
    Dec 3, 2021 at 12:27

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.