4

How do i iterate through a shapefile using shapely. This is my code but it keeps outputting the same id. I think that it keeps looking at the same record.

fc = fiona.open("file1.shp")
print fc.schema
for counter in range(0,50):    
    shapefile_record = fc.next()
    print shapefile_record['id']
14

fc.next() is a simple iterator:

fc = fiona.open("my.shp")
first_feature = fc.next()
second_feature = fc.next()
...

Or more simply:

for feat in fiona.open("my.shp")
     print feat

The result is a Python dictionary. For example with one result (feat=)

{'geometry': {'type': 'Point', 'coordinates': (180627.0, 330190.0)}, 'type': 'Feature', 'id': '154', 'properties': OrderedDict([(u'cadmium', 2.7), (u'copper', 27.0), (u'lead', 124.0), (u'zinc', 375.0), (u'elev', 8.261), (u'dist', 0.0122243), (u'om', 5.5), (u'ffreq', u'3'), (u'soil', u'3'), (u'lime', u'0'), (u'landuse', u'W'), (u'dist.m', 40.0)])}

As all dictionaries in Python, there are keys and values.

print feat.keys()
['geometry', 'type', 'id', 'properties']

So

print feat['id'] #gives the id
154
print feat['properties']['cadmium'] # gives the value of the cadmium attribute
2.7
print feat['geometry'] # gives the geometry, GeoJSON format
{'type': 'Point', 'coordinates': (180627.0, 330190.0)}

If you want to transform this geometry in a shapely geometry use the shape function:

print type(feat['geometry'])
<type 'dict'>
from shapely.geometry import shape
print shape(feat['geometry'])
POINT (180627 330190)
print type(shape(feat['geometry']))
<class 'shapely.geometry.point.Point'>

Final

 with fiona.open("my.shp") as input:
     for feat in input:
         geom = shape(feat['geometry'])
         id = feat['id']
         cadmium = feat['properties']['cadmium']
         ....

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.