3

I would like to select polygons that contain at least a point. I can use QGIS's tool called "Select by location: Select all buildings by location of point".

Is there a python alternative?

So far, I wrote a jupyter notebook and worked with GeoPandas.

I have tried

import pandas as pd

polygon_layer = gpd.read_file(r'file.shp') 
excel = pd.read_excel('file2.xlsx')

points_layer = gpd.GeoDataFrame(excel, geometry=gpd.points_from_xy(excel.X, excel.Y))

subset = gpd.sjoin(polygon_layer, points_layer, how='inner', predicate='within')

However, the spatial join does not work.

2
  • Do you get any error? You don't define a coordinate system for point layer. Dec 4, 2022 at 19:00
  • yes sir I do point.crs = {'init' : 'epsg:25832'}
    – Edo Grm
    Dec 4, 2022 at 21:02

1 Answer 1

6

In case of predicate='within', it searches polygons within the points. This is not possible.

Change predicate='within' to predicate='contains'.

1
  • Thank you sir, you are right. The right code is: subset = gpd.sjoin(polygon, points, how='inner', predicate='contains')
    – Edo Grm
    Dec 4, 2022 at 21:05

Your Answer

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

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