英文:
Python how many points are inside a municipality
问题
Here is the translated content:
我有两个空间数据集:
市政区
市政区 几何
1000 多边形 ((4.04305 47.56271, 4.04345 47.56303, ...
1001 多边形 ((-0.24733 45.88792, -0.24715 45.88820...
1002 多边形 ((-0.30449 45.91087, -0.30446 45.91120...
点
点 几何
200 点 (3617775.075 3205012.273)
201 点 (3617529.179 3205007.754)
202 点 (4375420.232 4093242.822)
我想估计每个市政区内有多少个点。其中一些点不会在任何市政区内,而某些市政区将有多个点。
这是我的代码:
import geopandas as gpd
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import pandas as pd
points = gpd.read_file("points.shp").to_crs("epsg:4326")
municipality = gpd.read_file("municipality.shp")
df = gpd.tools.sjoin(municipality, points, predicate="within", how='left')
df.index_right.unique()
array([nan])
我觉得很奇怪,没有任何点被插入到市政区。我做错了什么?任何帮助都将不胜感激。
英文:
I have two spatial datasets:
municipality
municipality geometry
1000 POLYGON ((4.04305 47.56271, 4.04345 47.56303, ...
1001 POLYGON ((-0.24733 45.88792, -0.24715 45.88820...
1002 POLYGON ((-0.30449 45.91087, -0.30446 45.91120...
points
points geometry
200 POINT (3617775.075 3205012.273)
201 POINT (3617529.179 3205007.754)
202 POINT (4375420.232 4093242.822)
I want to estimate how many points are inside each municipality. Some of these points will not be inside any municipality, some municipalities will have several points.
Here is my code:
import geopandas as gdp
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import pandas as pd
points= gdp.read_file("points.shp").to_crs("epsg:4326")
municipality= gdp.read_file("municipality.shp")
df= gdp.tools.sjoin(municipality, points, predicate="within", how='left')
df.index_right.unique()
array([nan])
I find it very weird that none of the points are inserted in a municipality. What I am doing wrong? Any help will be highly appreciated.
答案1
得分: 1
如果你想知道每个市政单位内的点数,可以执行以下操作:
municipality['num_points'] = municipality.geometry.apply(lambda x: x.contains(points.geometry).sum())
如果你想查看每个点属于哪个市政单位,可以执行以下操作:
points_by_municipality = gpd.sjoin(municipality, points).groupby('municipality', group_keys=True).apply(lambda x: x)
希望对你有帮助。
英文:
If you want to have the number of points inside each municipality you can do:
municipality['num_points'] = municipality.geometry.apply(lambda x: x.contains(points.geometry).sum())
If you want to see each point to what municipality it belongs to you can execute:
points_by_municipality = gpd.sjoin(municipality, points).groupby('municipality', group_keys=True).apply(lambda x: x)
Hope it works for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论