Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nachouve/760a7543f47d0a6a2b971f8aeac38432 to your computer and use it in GitHub Desktop.
Save nachouve/760a7543f47d0a6a2b971f8aeac38432 to your computer and use it in GitHub Desktop.
QGIS python script to update a field with a autoincrement value using an xy order of features.
##
# QGIS python script to update a field with a autoincrement value using an xy order of features.
# Created at: March 2018
import operator
# Attribute field to update
FIELD_TO_AUTOINCREMENT = 'id'
START_AT = 1 #0
layer = iface.activeLayer()
autoincrement_idx = layer.fieldNameIndex(FIELD_TO_AUTOINCREMENT)
a_feat = []
fid_new_values = {}
for f in layer.getFeatures():
bbox = f.geometry().boundingBox()
item = {'x': bbox.xMinimum(),'y': bbox.yMaximum(), 'id': f.id(), 'old_field': f['id']}
#print(item)
a_feat.append(item)
## Sorting
a_feat.sort(key=operator.itemgetter('x'))
#items that compare equal retain their original order.
a_feat.sort(key=operator.itemgetter('y'), reverse=True)
num = START_AT
for i in a_feat:
#print(i)
fid_new_values[i["id"]] = num
num = num + 1
layer.startEditing()
for feat in layer.getFeatures():
feat[autoincrement_idx] = fid_new_values[feat.id()]
layer.updateFeature(feat)
layer.commitChanges()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment