How to sum the number of entries in a dataframe that are located within a geopandas boundary

Viewed 100

I have two geodataframes: One containing sightings of animals of a specific species called bird_df (with location as points), and the other detailing the boundaries of each municipality within my state called map_df.

I want to use the geopandas method .contains(x) to count the number of animals that were found in each municipality and add that total to the boundaries dataframe so i can generate a choropleth.

My pandas is a bit rusty but I've tried things like map_df[map_df["geometry"].contains(bird_df["geometry"]) == True]

I just don't know how to wrap my head around this problem. Some help would be appreciated.

Thanks

1 Answers

I recommend using an sjoin for this.

import geopandas as gpd
import pandas as pd

# make some dummy points
df = pd.DataFrame()
df['x'] = [0.61, 0.62, 0.63, 0.64, 0.65]
df['y'] = [41.60, 41.62, 41.63, 41.64, 41.65]
points_gdf = gpd.GeoDataFrame(geometry=gpd.points_from_xy(df.x, df.y))

# buffer 2 rows of points to make some dummy polys
poly_gdf = points_gdf.head(2).copy(deep=True)
poly_gdf['geometry'] = poly_gdf['geometry'].buffer(0.02)

# do the spatial join, index right is the polygon idx values
sjoin_gdf = gpd.sjoin(points_gdf, poly_gdf)

# count the values with value counts
count_dict = sjoin_gdf['index_right'].value_counts().to_dict()

# map the count_dict back to poly_gdf as new point count column 
# alternatively you could do a join here, but new col name is nice
poly_gdf['point_count'] = poly_gdf.index.map(count_dict)

Output poly_gdf:

    geometry                                            point_count
0   POLYGON ((0.63000 41.60000, 0.62990 41.59804, ...   1
1   POLYGON ((0.64000 41.62000, 0.63990 41.61804, ...   2

Viz:

cat_df = pd.concat([points_gdf, poly_gdf])
cat_df.plot(facecolor="none")

enter image description here

Related