Geographic Information Systems Asked on March 31, 2021
I’m using the graphic modeler and ‘Add unique value index field’ algorithm to assign IDs to unique records in a vector layer which works great, but then I want to add a 2nd field that will autoincrement for each unique value created. I can use the ‘Add autoincremental field’ algorithm, but then I get 1 to n for my IDs, where I’d like it to re-start for each unique id.
Example: rather than 10-0, 10-1, 10-2, 11-3, 11-4 I’d like to see 10-0, 10-1, 10-2, 11-0, 11-1.
Bonus: If there’s a way to start the autoincremental number at 10 instead of 0, that would be even better!
You could create a custom script which increments the value index you created and saves these in a new field. You can create one from:
Processing Toolbox > Scripts > Tools > Create new script
Then use something like the following:
##Example=name
##Layer=vector
##Field_to_group_increment=field Layer
##New_index_field=string index
##Output=output vector
from qgis.core import QgsField, QgsVectorFileWriter, edit, QgsVectorLayer
from PyQt4.QtCore import QVariant
layer = processing.getObject(Layer)
writer = QgsVectorFileWriter.writeAsVectorFormat(layer, Output, "utf-8", None, "ESRI Shapefile")
output = QgsVectorLayer(Output, 'any_name', 'ogr')
idx = output.fieldNameIndex(Field_to_group_increment)
values = output.uniqueValues(idx)
with edit(output):
output.addAttribute(QgsField(New_index_field, QVariant.Int))
for feat in values:
x = 10
for feature in output.getFeatures():
if feat == feature[Field_to_group_increment]:
feature[New_index_field] = x
output.updateFeature(feature)
x = x + 1
del writer
Make sure to save the script into your /.qgis2/processing/scripts
directory. You can then run the script from the Processing Toolbox or include it in your model.
Example:
The interface when you run the script:
The result:
Correct answer by Joseph on March 31, 2021
If you download the next nightly of the QGIS 3.0 pre-release, it's now supported by the "Add autoincremental field" algorithm:
Answered by ndawson on March 31, 2021
With QGIS 3.x you can use the aggregate expression function "minimum" in a virtual field to autoincrement your numbers:
$id - minimum( $id,group_by:="group_field") + 1
If you want to start autoincremental number at 10 you have to replace "+ 1" with "+ 10".
Answered by christoph on March 31, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP