2

I'd like to create a new field in the attribute table which gives the rank of the polygon by size. For example, the polygon of the largest size would be rank 1 and the smallest rank N.

I was hoping sorting the table by shape size and then using $id would work, but that appears to be tied to the row ID #.

I am using QGIS.

2
  • Sorry, preferably QGIS, but I could also use ArcGIS. Do you mean to sort the table, Save As, and then copy the new FID/OID to the "Rank" field? I was hoping not to have to create a new shapefile...
    – user52505
    May 21 '15 at 20:48
  • Sort and save as won't work. Have to use a plugin - see gis.stackexchange.com/questions/148136 from this morning and linked questions there. But then yes, copy new FID field to Rank field. It would work and is the shortest/simplest method I know of off-hand. For incrementing ids in QGIS, might look at gis.stackexchange.com/questions/132346 but I don't know if it respects sort. Might be some other questions here on that.
    – Chris W
    May 21 '15 at 20:56
4

The following Python can be used to sort features by some attribute, here the area, and increment some field, here named 'Rank'. The field should exist. Make your polygon layer the active layer and paste the following code into Python console.

aLayer = qgis.utils.iface.activeLayer()  # get active layer
# create list of tupels of area and feature-id
aList= [(feat.geometry().area(), feat.id()) for feat in aLayer.getFeatures()]
aList.sort()  # sort list of tupels

i = 1
fni = aLayer.fieldNameIndex('Rank')  # get fieldindex
aLayer.startEditing()
for feat in aList:
    aLayer.changeAttributeValue(feat[1], fni, i)  # change field value
    i += 1

aLayer.commitChanges()  # save changed and stop editing

The code can be used in any case, where a field should be populated with an incremented value reflecting some sorting. Another use case is sorting by easting or northing, as in this thread (Create a reference number (id) based on x coordinate in QGIS).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.