简体   繁体   中英

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

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

完整的城市多边形

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?

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()

多边形数据框

point_cases.head()

点数据框

# 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.

输出

地图

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

unary_union merges all the shapes, getting rid of ward details, so there is no way to determine which ward the point intersects by using the union.

What you need is spatial index. GeoPandas does provide that via.sindex attribute, see eg this detailed manual how to use it: https://automating-gis-processes.github.io/site/notebooks/L3/spatial_index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM