7

I have a point shapefile and a polygon shapefile in QGIS. Now I want to use the point shapefile's value add to polygon shapefile (be a column in the end).

There are colors with each value, and make the color overlay on the polygon.

How to do it with Python??

2 Answers 2

7

See the PyQGIS Cookbook for advise how to add attributes to vector layers:
http://www.qgis.org/pyqgis-cookbook/vector.html#adding-and-removing-fields

However the easier way in your situation would be to do a simple spatial join to add your point values to the polygons.

4

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)

simple example enter image description here

Your Answer

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

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