3

What is preferred method to save reference from geometry to original feature when working with shapely geometries in python?

Ie. After creating STRtree and getting some result from it, there is no direct way to access feature f from which this geometry was created.

from shapely.geometry import shape
from shapely.strtree import STRtree
...
tree = STRtree([shape(f['geometry']) for f in features])

I guess there is something short easy and cheap as this is often used but can't find it or guess what it is? Dict comes first to mind but geometries are unhashable so?

0

2 Answers 2

3

The shapely STRtree documentation explicitly mentions how to deal with this in a note, I guess you missed it or even checking it might not have come to mind? https://shapely.readthedocs.io/en/stable/manual.html#strtree.STRtree

To get the original indexes of the query results, create an auxiliary dictionary. But use the geometry ids as keys since the shapely geometries themselves are not hashable.

index_by_id = dict((id(pt), i) for i, pt in enumerate(points))
[(index_by_id[id(pt)], pt.wkt) for pt in tree.query(Point(2,2).buffer(1.0))]
[(1, 'POINT (1 1)'), (2, 'POINT (2 2)'), (3, 'POINT (3 3)')]
1
  • OMG I missed it, saw only two methods documented for STRtree, all on less then one screen and thought what kind of documentation is this. Closed it without reading all :D May 17, 2021 at 12:50
0

Until nice answer found I have used this ugly hack to save data which I need:

def shape_save_props(feat):
    s = shape(feat['geometry'])
    s.properties = feat['properties']
    return s

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.