TransWikia.com

Adding unique ID for groups of items using field calculator in QGIS

Geographic Information Systems Asked by Elise on February 17, 2021

I have a set of string values in a shapefile’s attribute column and want to assign a number to them in a way that each unique string gets an integer number, like this:

enter image description here

How do I do this using the field calculator? I have 3,000 rows of data and 97 different names to do this for.

3 Answers

You can use arrays for this purpose:

 array_find(array_distinct(array_agg("Name")),"Name")

Which returns for example this id column:

enter image description here

So how does it work: First an array of all Name values is created, then every duplicate value gets deleted. At the end the index of the current name is searched in the array and the index used as id.

PS: not sure when array_find and array_distinct were introduced in QGIS. Only tested in 3.14. If you dont want zeros as id, simply add +1 to the expression.

Correct answer by MrXsquared on February 17, 2021

You can use pyqgis:

lyr = QgsProject.instance().mapLayersByName('lmv ok_my_riks_sample')[0] #Change name to match your data
category_field = 'kategori' #Same
field_to_calculate = 'cat' #Same. This integer field needs to be added before executing the code

unique_vals = lyr.uniqueValues(lyr.fields().indexFromName(category_field)) #Find all unique values
#{'Sankmark', 'Tätort', 'Skogsmark', 'Vattenyta', 'Öppen mark'}

d = {cat:e for e,cat in enumerate(unique_vals, 1)} #Create a dictionary of unique values and number #Create a dictionary of unique values and number
#{'Sankmark': 1, 'Tätort': 2, 'Skogsmark': 3, 'Vattenyta': 4, 'Öppen mark': 5}

#Update field using dictionary
with edit(lyr):
    for feat in lyr.getFeatures():
        feat.setAttribute(feat.fieldNameIndex(field_to_calculate), d[feat[category_field]])
        lyr.updateFeature(feat)

enter image description here

Answered by BERA on February 17, 2021

This is a typical Case..When..Then solution. In the field calculator, you can use the following statement to update the ID field:

Case
When “Name” = ‘loam’ then 1
When “Name” = ‘silt’ then 2
When “Name” = ‘sand’ then 3
.
.
Else 20
End

You can add other cases for other names and assign them ids as you like. the Else is to provide one value for the remaining names.

Answered by ahmadhanb on February 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP