Tuesday, 21 August 2018

qgis - Is there a python option to "join attributes by location"?


I am trying to perform the function join attributes by location as found on the QGIS menu Vector>Data Management Tools. I am seeking an open source python option for this. I know arcpy has a spatial join function but I'm trying to perform this outside of the ESRI environment.



Answer




You may want to take a look at Shapely and Fiona. Fiona is a wrapper for gdal to make spatial file import and export easy. Shapely provides geometry functionality. Here is a very simple example to give you the idea. It joins polygon attributes to all points within that polygon.


The example data I have used are these polygons and these points.


import fiona
from shapely.geometry import shape
from copy import deepcopy

with fiona.open("planning_neighborhoods.shp", "r") as n:

with fiona.open("Schools_Private_Pt.shp", "r") as s:


# create a schema for the attributes
outSchema = deepcopy(s.schema)
outSchema['properties'].update(n.schema['properties'])

with fiona.open ("Schools_withNbhd.shp", "w", s.driver, outSchema, s.crs) as output:

for school in s:
for neighborhood in n:
# check if point is in polygon and set attribute
if shape(school['geometry']).within(shape(neighborhood['geometry'])):

school['properties']['neighborho'] = neighborhood['properties']['neighborho']
# write out
output.write({
'properties': school['properties'],
'geometry': school['geometry']
})

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...