InsideDarkWeb.com

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.

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!

Related Questions

How to open shapefile dataset using ArcGIS Pro SDK .NET?

1  Asked on June 24, 2021 by pavel-butusov

   

GRASS 6.4.3 Crashes on Startup; libintl-8.dll cited

4  Asked on June 24, 2021 by darin

     

Plotting polygons as separate plots using Python

3  Asked on June 23, 2021 by ralt_jol

       

Seeking formula for Distance Calculation on Mars

0  Asked on June 23, 2021 by douglas-marsh

     

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.