9

I'd like to use the field calculator in QGIS to create a unique feature (polygon) id that reflects different levels in a geographic hierarchy. So say I have a REGION attribute within which there are several AREAS (unique features). I have alphanumeric codes for the REGIONS, but within each I want to number the AREAS in sequence from 1 to whatever. The order doesn't matter. So the final unique ids would look something like:

GY001, GY002, GY003... DL001, DL002...

If I didn't want to start over again for each REGION, I would just calculate it as

concat(REGION, $rownum+1)

But how to restart the numbering for each REGION?

3
  • 1
    Which kind of dataprovider are you using? If it's a database SQL could be an option. If not, would a python script also be an acceptable approach? Commented Sep 8, 2015 at 20:48
  • I think that's a little beyond the QGIS field calculator; it could be done in the Esri field calculator (if that's an option). You will need to write python code for this and keep a track of your regions and cumulative variables in a dictionary object. Commented Sep 8, 2015 at 22:57
  • Sorry for the delay in replying - it's been one of those weeks. The dataset is a shapefile. I've a colleague who may have access to the ESRI field calculator at some stage. I've not dabbled my toes in python scripts before, but wouldn't be averse to learning. Would this be a good problem to start with? If so, pointers to any gentle guides to starting to write python scripts would be welcome.
    – blackthorn
    Commented Sep 11, 2015 at 13:21

2 Answers 2

4

With QGIS 3 you can use this simple expression in field calculator:

array_find(array_agg($id,"groupfield"),$id)+1

Simply change "groupfield" to the name of your group field. You can delete +1 if you want your IDs to start at 0.

To concat with the groupfield and add leading zeros you can use lpad() and concat(). Here it adds four leading zeros:

concat("groupfield",lpad(array_find(array_agg($id,"groupfield"),$id)+1,4,0))
1

If the area code number order does not matter you can try this:

  1. Calculate the number of similar "REGION" features with count(expression, group_by, filter)

  2. Order the shapefile according to "REGION". Its possible to do by MMQGIS plugin "sort-tool"

  3. Make unique "id" for all areas in field calculator with @row_number

  4. Count numbers for areas in field calculator

"id" % "counted_areas" +1

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.