I have a shapefile of polygons, and a list of mean values of the area in each polygon. I need to assign said mean values to each polygon. How would I go about this using GDAL/OGR in Python?


I'm making the assumption that if you have a list of mean values for each polygon, you also have an ID for that polygon in that list. Otherwise your mean values don't really help you much. All you have to do is a join.

So as an example, if your polygon layer is named mypolys and it has an ID field and your table (a csv file?) is named mycsv.csv and it has a field (ID) and their types match, you should be able to do the following.

ogr2ogr -sql "select mypolys.*, mycsv.* from mypolys left join 'mycsv.csv'.csv on mypolys.ID = mycsv.ID" OUTPUT.shp mypolys.shp

EDIT: If you only do this once, I think it makes sense to just do a join. If you really want to do it with code, you can do a join with ogr in python. You will have to look up the specifics of that online using resources like "GDAL/OGR in Python" but this should get you started with the library within python ...

from osgeo import ogr

You can see this link on OGR SQL for more information (or if the specific join code I put here doesn't work quite right).

  • I have the list from the zonal statistics code from the Python OGR cookbook. The list is actually a dict, with ID and mean value. Is there a way to do this in code or is it easier to print and the join through ogr2ogr? – user81442 Aug 27 '16 at 18:20

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.