Wednesday, 13 September 2017

Calculating unique ID value for a field in QGIS using python


I am trying to calculate a unique ID field for a vector layer in qgis, using python. I found some code to calculate attribute values, and tried to increment the value in the expression, but it doesn't work - it calculates all feature values as 0. I'm guessing the intial value I set for the expression is what it is reading each time - it doesn't seem to change it inside the loop. Anyone have any ideas? Here is my code:


QgsMapLayerRegistry.instance().addMapLayer(dsslvExplodeLyr)

idx = dsslvExplodeLyr.fieldNameIndex('UniqueID')

eVal = '0'
e = QgsExpression(eVal)

e.prepare(dsslvExplodeLyr.pendingFields())

dsslvExplodeLyr.startEditing()

for f in dsslvExplodeLyr.getFeatures():
num = int(eVal)
num = num + 1
eVal = str(num)
f[idx] = e.evaluate(f)
dsslvExplodeLyr.updateFeature(f)


dsslvExplodeLyr.commitChanges()

I should mention I've also tried '$rownum' for the expression as that works in the field calculator gui but it also just gives a value of 0.



Answer



I'm not sure how that was going to work with the str(num) and int(eVal), it seems to me that the values are being overwritten on each iteration. Try it this way:


QgsMapLayerRegistry.instance().addMapLayer(dsslvExplodeLyr)

idx = dsslvExplodeLyr.fieldNameIndex('UniqueID')


eVal = '0'
num = 0
e = QgsExpression(eVal) # where does 'e' come into it? leaving it here because it may have other uses (undisclosed)
e.prepare(dsslvExplodeLyr.pendingFields())

dsslvExplodeLyr.startEditing()

for f in dsslvExplodeLyr.getFeatures():
eVal = str(num) #I'm assuming that the field 'UniqueID' is a string, isn't it?
f.setAttribute(idx,eVal) # set the value for the field, aslo works with field name

dsslvExplodeLyr.updateFeature(f)
num += 1 # post iterate, so the first is 0, second is 1 and so on.

dsslvExplodeLyr.commitChanges()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...