How to find inside which multipolygon of a GeoPandas DataFrame a point lies?

Viewed 1014

I downloaded a geojson file of a city and was able to load it using geopandas. The city is made up of different wards each of which is a MultiPolygon. Now to check if a point lies inside the city or not, I did a union of all the rows of the dataframe and created a polygon of the whole city. This way I was able to check where the point lies without iterating through the whole dataframe

complete city polygon

city = unary_union(city_geodf['geometry'])
city.contains(point)

Now the problem is, I want to find inside which ward specifically that point lies, and the only way I can think of doing that is to iterate through the whole dataframe. Is there any efficient way to solve this? Like when I am checking if a point is inside the city, can it also return the ward number?

2 Answers

Use a spatial join with the function sjoin from geopandas package (https://geopandas.org/reference/geopandas.sjoin.html), to use this function you must be sure that rtree package is available.

After load your dataframes (polygons and points). I use two geopackages just change it for your geojson files.

import geopandas as gpd
polygon_area = gpd.read_file('urban_atlantico.gpkg', layer='urban_atlantico')
point_cases = gpd.read_file('cases.gpkg', layer='cases')

polygon_area.head()

polygon_dataframe

point_cases.head()

point dataframe

# geopandas.sjoin(left_df, right_df, how='inner', op='intersects',
#                 lsuffix='left', rsuffix='right')
df_out = gpd.sjoin(point_cases, polygon_area, how='left', op='within')

The column index right gives you an index for the polygon where the point is. If this column is NaN the point is out of any polygon.

output

map

If you get an error with this message:

UserWarning: Cannot generate spatial index: Missing package `rtree`.
warn("Cannot generate spatial index: Missing package `rtree`.")

You must be install rtree, for example in Ubuntu or Google Collab

sudo apt-get update 
sudo apt-get install -y libspatialindex-dev
sudo apt-get install -y python-rtree
pip install rtree
Related