Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

How can I sort the features of an ogr layer by the values of a field? I tried naive variations of

def sortlayer(ds, layer, field):
    lname = layer.GetName()
    lsort = ds.ExecuteSQL(b'select * from "{}" order by {}'.format(lname, field))
    ds.DeleteLayer(lname)
    ds.CopyLayer(lsort, lname)

but this either crashed or freezed.

Bonus points for a solution that doesn't change the order of layers in the datasource and/or that doesn't rely on unique layer names.

Actually the datasources are in-memory (memory-driver), and I may have up to 10 layers with up to 10.000 features over all.

Maybe it would be better not to use SQL but create an index as list, and then swap features around in the layer with Layer.GetFeature()/.SetFeature()?

Thanks, Redoute

share|improve this question
    
Please post your solution as an answer if it solves the problem you had. People can then comment on the answer and upvote it. You can even accept it once it gets some upvotes. –  underdark Jun 9 '13 at 20:47
    
@underdark: Done, I really didn't find the answer button last time. :-) –  Redoute Jun 11 '13 at 9:52
add comment

1 Answer

I followed the second approach now and this seems to work, comments welcome:

def sortlayer(l, fd):
    # fids are unique, fids may be sorted or unsorted, fids may be consecutive or have gaps
    # don't care about semantics, don't touch fids and their order, reuse fids
    fids = []
    vals = []
    l.ResetReading()
    for f in l:
        fid = f.GetFID()
        fids.append(fid)
        vals.append((f.GetField(fd), fid))
    vals.sort()
    # index as dict: {newfid: oldfid, ...}
    ix = {fids[i]: vals[i][1] for i in xrange(len(fids))}

    # swap features around in groups/rings
    for fidstart in ix.keys():
        if fidstart not in ix: continue
        ftmp = l.GetFeature(fidstart)
        fiddst = fidstart
        while True:
            fidsrc = ix.pop(fiddst)
            if fidsrc == fidstart: break
            f = l.GetFeature(fidsrc)
            f.SetFID(fiddst)
            l.SetFeature(f)
            fiddst = fidsrc
        ftmp.SetFID(fiddst)
        l.SetFeature(ftmp)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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