1

I have a layer with a repeating field name, thus different groups of features (I also have a numerical group field). How can I add a field group_id, using QGIS expressions? What I want is kind of a uniqe identifier per group, counting from 1 to the last element contained in the group (see screenshot).

What I tried: Using array_length (array_agg( "group", "group")), I get the number of features per group (field no_in_group). With generate_series (1, [features per group]), I get an array, counting from 1 to the last no. of each group.

However, I'm stuck how to assign each element of the array to one feature of the group. I suppose that array_foreach () will do the job, but I'm unsure how to use it in this case.

Screenshot: the field with red outline is what I want to get: a unique, incrementing id, starting from 1 for each group. Here, I introduced the values manually to make clear what I'm looking for: enter image description here

Babel
  • 71,072
  • 14
  • 78
  • 208

1 Answers1

2

I know you asked for a QGIS expression solution but I came up with a quick Python solution which does the job. Just run this as a script while the layer is active.

layer = iface.activeLayer()

#order by group request = qgis.core.QgsFeatureRequest() clause = qgis.core.QgsFeatureRequest.OrderByClause("group", ascending=False) orderby = qgis.core.QgsFeatureRequest.OrderBy([clause]) request.setOrderBy(orderby)

current_group = None last_group = None with edit(layer): for f in layer.getFeatures(request):

    current_group = f["group"]
    if current_group != last_group:
        id = 1
    else:
        id += 1

    last_group = current_group
    f["group_id"] = id
    layer.updateFeature(f)

The result:

enter image description here

Note: Run this in the script editor window, not the console. enter image description here

Leon Powałka
  • 1,653
  • 5
  • 18