2

I have two polygon shapefiles. I'd like to spatially join them in Geopandas based on their centroids. Basically doing the same thing as have_their_centers_in in ArcGIS but with GeoPandas.

I see the options GeoPandas has for predicates like within and intersects but I don't see a way to use the centroids of the shapefiles. I've tried using shapely's centroid but I'm not sure how to implement it. Is there any way to do this in GeoPandas?

Here's some code I'm using:

for layer in boundaries:
    if layer == layers[0]:
        sj_layer = gpd.read_file(boundary_path,layer=layer)
        sj_stack = gpd.sjoin(stacked,
                         sj_layer,
                         how="left",
                         op=geometry.centroid?)
        sj_stack

1 Answer 1

1

You can create a centroid column, set the geometry to it, spatial join and switch back to the polygom geometry:

import geopandas as gpd
    
df1 = gpd.read_file(r"C:\GIS\data\Bakgrundskartor_LMV\vk_riks_Sweref_99_TM_shape\vagk\riks\rutnat.shp")
df2 = gpd.read_file(r"C:\GIS\data\Bakgrundskartor_LMV\Hamta_data_ladda_postgis\sve_1milj_Sweref_99_TM_shape\svk\riks\ak_riks.shp")

df1['centroid'] = df1.geometry.centroid #Create a centroid point column
df1['polygeom'] = df1.geometry #Save the polygon geometry to switch back to after the join

df1 = df1.set_geometry('centroid')

#df1.geometry.head(1)
#0    POINT (785000.000 6325000.000)

df = gpd.sjoin(df1, df2, how="left", predicate="intersects")
df = df.set_geometry('polygeom')

#df.geometry.head(1)
#0    POLYGON ((780000.000 6330000.000, 790000.000 6...

df = df[[column for column in df.columns if column not in ('centroid','polygeom')]] #Drop the created columns
2
  • 1
    This worked perfectly. I crossed referenced the results with results from ArcGIS and they are the same as far as I can tell. It also appears to be faster at least with dataset I'm working with with almost a million shapes.
    – Nick C
    Commented Oct 15, 2022 at 14:13
  • Couldn't you just do an inner_join with the sjoin and not have to implement the final line?
    – James
    Commented Mar 11 at 22:11

Your Answer

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

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