2

I need to add a field into these shapefile rows which are sequentially numbered when ordered by either the X or Y axis.

I have had success with this by using the sort and number QGIS plugin, however I have only managed to be able to perform this manually row by row. My full dataset will have over 100 rows, so is there a way to be able to perform this as a batch process?

Other processes I have executed the batch process from the toolbox with a right click, but as it is a plugin, I can't find a way to perform this.

Point data in rows

Comrade Che
  • 7,091
  • 27
  • 58
Pipnib_TDG
  • 23
  • 5
  • Can you share your data? – Comrade Che Sep 23 '22 at 16:05
  • In my opinion, the approach to solving the problem is very much like this: https://gis.stackexchange.com/q/409386/35561 – Comrade Che Sep 23 '22 at 16:25
  • 1
    I see your problem has been solved, but if you have multiple features in a single layer and would like to renumber by following a custom line instead of x/y coords, you can also try this virtual layer method outlined here (still dreaming for the day some smart cookie can convert this to a python plugin). https://gis.stackexchange.com/a/328813/98784 – she_weeds Sep 29 '22 at 01:57

1 Answers1

1

You can use pyqgis. This will process all layers added to the map and add an id field and numbering. Adjust fieldname and wether to sort by x or y and only add the shapes you want to process to the map:

fieldname = 'idfield' #Name of the field to add

for layer in QgsProject.instance().mapLayers().values(): #For all layers added to the map (add only the shapefiles) print(layer) layer.dataProvider().addAttributes([QgsField(fieldname, QVariant.Int)]) #Add the new field layer.updateFields() fieldindex = layer.fields().indexOf(fieldname) #Find index of the new field all_features = [f for f in layer.getFeatures()] #List all features/points all_features.sort(key=lambda f: f.geometry().asPoint().x()) #Sort by x coordinate. Change .x to .y to sort by y coord attributemap = {} #A dictionary to hold feature id, fieldindex and number for e, f in enumerate(all_features, 1): attributemap[f.id()] = {fieldindex: e} # #{30: {6: 1}, 28: {6: 2},... } So feature 30 should in field 6 get the value 1 layer.dataProvider().changeAttributeValues(attributemap) #Update the new field with numbers

enter image description here

enter image description here

BERA
  • 72,339
  • 13
  • 72
  • 161
  • 1
    Hi, sorry for the delay in responding - I'm very new to python but I have finally figured it out and got it working, it gives exactly what I need so thank you very much! – Pipnib_TDG Sep 26 '22 at 08:44