5

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.

asked Apr 1, 2014 at 21:28

2 Answers 2

9

Sure.

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

It's documented at https://fiona.readthedocs.io/en/latest/manual.html#slicing-and-masking-iterators

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.

bugmenot123
12.3k4 gold badges42 silver badges84 bronze badges
answered Apr 2, 2014 at 2:13
1
  • 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. Commented Mar 13, 2016 at 2:04
1

If you want to select by a list of attributes you can do something like this:

import fiona
inp_list = ['region1','region2','region3']
with fiona.open("OriginalShape.shp") as input:
 meta = input.meta
 with fiona.open('OutputShape.shp', 'w',**meta) as output:
 for feature in input:
 if feature['properties']['foo'] in inp_list:
 output.write(feature)

This will create a new shapefile with only the selected attributes.

answered Jun 29, 2021 at 20:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.