2

I have some polygons and points that I know overlay which look like this:

enter image description here

One thing to note is that in the polygon shapefile there can be multiple which overlap and I want to intersect through all of them, thus a single point could potentially return numerous rows in the output. I have been trying this code:

from shapely.geometry import *

import geopandas as gpd
pts = gpd.read_file("/path.shp")
poly = gpd.read_file("/path.shp")

combined = pd.DataFrame()
for key , grp in pts.groupby('id'):
    inter = poly.intersects(grp['geometry']).to_frame()
    combined = combined.append(inter)

but the output of combined returns False for every single instance. Is there anyway to intersect points and polygons in geopandas or shapely? id is just the row indicator for each point.

2
  • What is the desired output you are looking for? A dataframe indicating for each point which of the polygons it intersects?
    – joris
    Jun 22, 2018 at 16:40
  • Each of the polygons has a Year column. I ultimately want to know what the year is for each point. I can determine this myself though if the correct True and False intersections occur though. Jun 22, 2018 at 17:27

1 Answer 1

3

I think what you want is a "spatial join", where we add information of the second dataframe (the polygons, which have the YEAR information) to the first dataframe (the points) based on their spatial relationship:

gpd.sjoin(pts, poly[['YEAR', 'geometry']], how='left', op='intersects')

This adds a new column to the pts dataframe with the YEAR of the polygon in which the point is located. When a point is located in multiple polygons, that point it row will be repeated with the different values for YEAR


Additional note on why your approach gave all False values:
In inter = poly.intersects(grp['geometry']), geopandas will check for each polygon in poly if it intersects the specified geometry, if the specified geometry is a single scalar geometry. However grp['geometry'] is (as far as I can see from the code) not a scalar value. In such a case, poly and grp['geometry'] are aligned on their index, and then the intersects operation is done element-wise (polygon 1 with point 1, polygon 2 with point 2, etc). This is not what you want in this case.

1
  • Yes I was looking for this exactly and thought it was weird to loop through each row. Not sure if you contribute to geopandas or not but I find the package immensely useful Jun 22, 2018 at 18:37

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.