# Sorting grid cells in fishnet grid by location and number using QGIS?

I am using QGIS 3.2.0 on a Mac (and also have QGIS 2), and I have a fishnet grid (probably created in Arc) that comprises of nearly 2 million grid cells. As a result, every change I make to the attribute table takes hours, so I can't experiment as I would usually.

I need to label each grid cell such that the north-westernmost cell is "1", and the numbers proceed by rows, until the last number goes into the south-easternmost cell. Using the row-number doesn't work, as that's not how the table is sorted. I've done this before, but cannot remember how.

• You want to give each fishnet an ID, starting from top left, ending at bottom right?
– BERA
Sep 22, 2018 at 18:31
• Yes, exactly that. Sep 22, 2018 at 18:37
• See also this here: gis.stackexchange.com/a/361838/88814 Dec 27, 2020 at 19:00

## 1 Answer

You can use pyqgis.

Script will:

1. List all centroids x, y coordiantes with each features id
2. Sort list by x and y
3. The ids are now in correct order - create a dictionary of id and sequential number using enumerate: `attrMap = {feature id: {field index: order}, ...}`
4. Use dictionary with id as key and update field

Add your layer to the map, add a integer field to hold the numbers and execute.`

``````layer = iface.activeLayer() #Click layer in layer tree
idfield = 'fishnetID' #Change to match the name of your field

coords = [[round(f.geometry().centroid().asPoint().x(),0),round(f.geometry().centroid().asPoint().y(),0),f.id()] for f in layer.getFeatures()]
coords.sort(key=lambda k: (k[1],-k[0]), reverse=True)
order = [i[2] for i in coords]

i = layer.fields().indexFromName(idfield)
attrMap = {id: {i:e} for e,id in enumerate(order,1)}
layer.dataProvider().changeAttributeValues(attrMap)
``````