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:
strings numbers ------- ------- Cloud 1 Water 2 Water 2 Vegetation 3 Water 2 Cloud 1 Cloud 1 Vegetation 3
The order does not matter (but of course, if it's possible, alphabetically would be perfect).
Is there a way to achieve this without knowing the actual strings or the count of unique strings (assuming I have 20-30 different strings)?
I am using Python in QGIS 3.
Using the suggestion of BERA, I was able to run the Python script from the console. Then I tried to implement it as an expression:
from qgis.core import * from qgis.gui import * from qgis.utils import iface @qgsfunction(args='auto', group='Custom') def numberUniqueStrings(layer_name, src_column, dst_column, feature, parent): layer_list = QgsProject.instance().layerTreeRoot().children() layer = [lyr.layer() for lyr in layer_list if lyr.name() == layer_name] idx = layer.getFeature(1).fieldNameIndex(dst_column) unique =  with edit(layer): for feature in layer.getFeatures(): value = str(feature[src_column]).strip() if value not in unique: unique.append(value) counter = unique.index(value) + 1 feature.setAttribute(idx, counter) layer.updateFeature(feature)
and called it using the "Field Calculator" (created the field "numbers" as integer before):
numberUniqueStrings(@layer_name, "strings", "numbers")
Unfortunately nothing happens, all the fields stay empty.