Is it possible to select polygons from a shapefile based upon their attributes using the Fiona Python module? I can't seem to find anything in the docs, but it seems like a strange thing not to be included in the module.

All I can think of at the moment is iterating through all the polygons, doing the calculations I want to do, and then storing the data in a database, or some other data structure, and then running my SELECT query over that.

Alternatively if there is another Python module that will do this easily then that would be great to know about.

Sure.

import fiona

with fiona.open("file.shp") as src:
    filtered = filter(lambda f: f['properties']['foo']=='bar', src)

It's documented at http://toblerity.org/fiona/manual.html#filtering.

The thing is: shapefiles don't have standard and interoperable attribute indexes and so you have to loop over all features and test them no matter what. If you want high performing indexes, load your shapefiles into a relational database and create all the indexes you need.

  • thanks for the soln @sgillies, when I try to do sink.write(feature), it does not create anything in the attribute table of the new shapefile. Any idea why? I am happy to create a new question. – user1186 Mar 13 '16 at 2:04
  • The link's anchor is gone, I guess toblerity.org/fiona/manual.html#slicing-and-masking-iterators is the recommended way to go nowadays. – bugmenot123 Oct 20 '16 at 19:49

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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