Fill with @row_number based on group field in QGIS 3
Do you need to use a field calculator? If not, the "Add autoincremental field" algorithm from the processing toolbox does what you want including the grouping.
References:
- How to Add Auto Increment Field in QGIS
If you know the row number of the beginning of each group, you can create a group_row_number field in the Field Calculator with a simple case when
statement.
In my example, I have groups A, B, C and D. Group A is rows 1-4. Group B is rows 5-8. Group C is rows 9-12. Group D is rows 13-17.
Field Calculator expression:
Result:
The generalized formula is:
case
when "groupfieldname" = 'first group name' then @row_number
when "groupfieldname" = 'second group name' then @row_number - [final_row_number_of_first_group]
when "groupfieldname" = 'third group name' then @row_number - [final_row_number_of_second_group]
...
end
Credits to @Gabriel De Luca from his answer https://gis.stackexchange.com/a/364575/99589
In the Field Calculator use the following expression array_find(array_agg($id,"group"),$id)+1
, where "group"
is an attribute that will restart the count when a new group appears.