Skip to content

Instantly share code, notes, and snippets.

@mlaloux
Created April 12, 2013 14:17
Show Gist options
  • Save mlaloux/5372329 to your computer and use it in GitHub Desktop.
Save mlaloux/5372329 to your computer and use it in GitHub Desktop.
If you want to use Python, you don't need QGIS, except if you want to create a plugin. In this case, you should consider PyQGIS with the reference given by Curlew
But you can also use Python modules like pyshp, osgeo (gdal and ogr) or Fiona and Shapely without QGIS
In both cases, you need a join field that will link the polygon shapefile to the point shapefile.
Example with Fiona and Shapely (all the elements of a shapefile (schema,geometry, records) are processed using Python dictionaries).
With ogr and Fiona it is easier to create a new shapefile, copying the original shapefile (geometry and attributes), and adding new fields with the desired values than modify the original shapefile.
from shapely.geometry import mapping
import fiona
# open the polygon shapefile
with fiona.collection('polygon.shp', 'r') as polygon:
# copy of the schema of the original polygon shapefile to the output shapefile (copy)
schema = polygon.schema.copy()
# creation of the new field color in the new schema
schema['properties']['color'] = 'str'
# output shapefile with the new schema
with fiona.collection('join_poly_pt.shp', 'w', 'ESRI Shapefile', schema) as output:
# open the point shapefile with colors
with fiona.collection('point.shp', 'r') as points:
polygons = [elem for elem in polygon]
points = [elem for elem in point]
# joint
for poly in polygons:
for pt in points:
# common field for the join
if poly['properties']['test'] == pt['properties']['test']:
# construction of the new shapefile
res = {}
res['properties'] = poly['properties']
res['properties']['color'] = pt['properties']['color']
# geometry of of the original polygon shapefile
res['geometry'] = mapping(shape(poly['geometry']))
output.write(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment