QGIS Group By Unique Value – Group by Unique Value Then Count Number of Elements and List Them

qgis

In QGIS3+ Field Calculator I am trying to group features by unique values in field 1 then assign a number (no matter the order) from 1 to n (n=number of elements grouped for each unique value in field 1) to populate field 2. The result should be something like:

feature field1  field2
1   Andree  1
2   Andree  2  
3   Andree  3
4   Luka    1
5   Luka    2   

Sounds pretty simple to me and I know how I would it in R, for example. But I really cannot think about a way to do it in QGIS expression builder and without using CASE WHEN-like expressions for every value in field 1; though there are different questions (among others, here or here) that I guess point to the right direction (using aggregation and arrays), I really don't grasp how to:

  • Access/group by every value in field 1
  • Assign a unique value to every feature from an array-type list

There are a couple of doubts above, but I'm looking for an answer to my first query.

Best Answer

Use this expression (you could also replace $id with feature in your case as this field apparently is also kind of an id):

array_find (
    array_agg( $id, group_by:=field1),
    $id
)+1

enter image description here

Related Question