TransWikia.com

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

Geographic Information Systems Asked by StripyDonkey on November 12, 2021

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.

One 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)

enter image description here

Answered by BERA on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP