How to add a column in QGIS via Python

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.


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

Tags:

Python

Qgis