Skip to content

Instantly share code, notes, and snippets.

@derek-watson
Created December 7, 2017 15:29
Show Gist options
  • Save derek-watson/4e2d6a1a4101d89eaeac338fbcd0a61b to your computer and use it in GitHub Desktop.
Save derek-watson/4e2d6a1a4101d89eaeac338fbcd0a61b to your computer and use it in GitHub Desktop.
from shapely.geometry import shape, mapping
from shapely.ops import unary_union
import fiona
import itertools
with fiona.open('Data/NonRegulatoryLayers_Subset.shp') as input:
# preserve the schema of the original shapefile, including the crs
meta = input.meta
with fiona.open('Out/dissolved.shp', 'w', **meta) as output:
# groupby clusters consecutive elements of an iterable which have the same key
# so you must first sort the features by the target property
prop = 'Ranked_Sol'
e = sorted(input, key=lambda k: k['properties'][prop])
# group by the prop field
for key, group in itertools.groupby(e, key=lambda x:x['properties'][prop]):
properties, geom = zip(*[(feature['properties'], shape(feature['geometry'])) for feature in group])
# write the feature, computing the unary_union of the elements in the group with the properties of the first element in the group
output.write({
'geometry': mapping(unary_union(geom)),
'properties': properties[0]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment