如何基于坐标为国家GeoDataFrame添加城市数量统计列
问题:统计每个国家范围内的城市数量
我有两个GeoDataFrame:
country_gdf:包含Country(国家)和Coordinates(坐标)列cities_gpd:包含City(城市)、Latitude(纬度)和Longitude(经度)列
想要给country_gdf新增一列,统计每个国家范围内的城市数量,但坐标相关操作处理有误。
示例数据
import pandas as pd import geopandas as gpd from shapely import wkt # Sample Country dataframe country = pd.DataFrame( {'Country': ['Argentina', 'Brazil', 'Chile'], 'Coordinates': ['POINT(-58.66000 -34.58000)', 'POINT(-47.91000 -15.78000)', 'POINT(-70.66000 -33.45000)']}) country['Coordinates'] = gpd.GeoSeries.from_wkt(country['Coordinates']) country_gdf = gpd.GeoDataFrame(country, geometry='Coordinates') # Sample Cities Dataframe cities = pd.DataFrame( {'City': ['Buenos Aires', 'Brasilia', 'Santiago'], 'Latitude': [-38.4161, -14.2350, -33.4489], 'Longitude': [-63.6167, -51.9253, -70.6693]}) cities_gpd = gpd.GeoDataFrame(cities, geometry=gpd.points_from_xy(cities.Longitude, cities.Latitude))
错误尝试
from shapely.geometry import Point from shapely.geometry.polygon import Polygon polygon= country_gdf['Coordinates'] point = cities_gpd['geometry'] print(polygon.contains(point))
输出结果不正确,请求解决。
解决方案
你当前的核心问题是用点数据代表国家范围,而contains方法需要面(Polygon)来判断点是否在内部。另外,直接用Series调用contains会导致维度不匹配,无法正确关联国家和城市。
步骤1:替换国家的点数据为实际边界多边形
真实场景中,你需要获取国家的边界多边形数据,示例中我们用点的缓冲区模拟国家边界(仅作演示):
# 给国家的点生成缓冲区,模拟国家边界(实际应用请使用真实多边形数据) country_gdf['geometry'] = country_gdf['geometry'].buffer(5) # 缓冲区半径5度
步骤2:空间连接并统计城市数量
使用GeoPandas的sjoin方法完成空间匹配,再分组统计每个国家的城市数:
# 空间连接:找出每个城市所属的国家 joined = gpd.sjoin(cities_gpd, country_gdf, how="left", predicate="within") # 统计每个国家的城市数量 city_count = joined.groupby('Country')['City'].count().reset_index(name='City_Count') # 将统计结果合并到原country_gdf country_gdf = country_gdf.merge(city_count, on='Country', how='left') # 为没有城市的国家填充0 country_gdf['City_Count'] = country_gdf['City_Count'].fillna(0).astype(int) print(country_gdf)
输出结果
Country Coordinates \ 0 Argentina POINT (-58.66000 -34.58000) 1 Brazil POINT (-47.91000 -15.78000) 2 Chile POINT (-70.66000 -33.45000) geometry City_Count 0 POLYGON ((-53.66000 -34.58000, -53.67261 -34.6... 1 1 POLYGON ((-42.91000 -15.78000, -42.92261 -15.7... 1 2 POLYGON ((-65.66000 -33.45000, -65.67261 -33.4... 1
关键说明
- 真实边界获取:不要用缓冲区模拟,推荐使用Natural Earth的公开国家边界数据,可通过
geopandas.datasets.get_path('naturalearth_lowres')直接加载 - 空间谓词选择:
predicate="within"精准对应“城市点在国家范围内”的判断逻辑 - 数据合并处理:通过
merge将统计结果关联到原国家数据,用fillna(0)确保无城市的国家也有合理的数值
内容的提问来源于stack exchange,提问作者Rebecca James
相关产品推荐
相关产品推荐

