Geopandas dissolve函数持续运行无终止的问题求助
Geopandas dissolve函数持续运行无终止的问题求助
各位大佬好,我最近在尝试用Geopandas的dissolve函数聚合几个国家时遇到了麻烦——这个函数一直跑个不停,完全没有终止的迹象。下面是我的最小复现代码,方便大家排查问题:
import geopandas as gpd shape='/Volumes/TwoGb/shape/fwdshapfileoftheworld/' countries=gpd.read_file(shape+'TM_WORLD_BORDERS-0.3.shp') # 添加列 countries['wmosubregion'] = '' countries['dummy'] = '' country_count = len(countries) # 如果国家列表为空则使用所有国家 country_list=['SO','SD','DJ','KM'] default = 'Null' for i in range(country_count): countries.at[i, 'wmosubregion'] = default if countries.ISO2[i] in country_list: countries.at[i, 'wmosubregion'] = "EAST_AFRICA" print(countries.ISO2[i]) region_shapes = countries.dissolve(by='wmosubregion')
我用的是TM_WORLD_BORDERS-0.3的shape文件,这个文件是免费可获取的。
问题排查与解决思路
我看了你的代码,发现导致dissolve一直运行的核心原因很明确:你把除了那4个目标国家之外的所有国家都标记成了"Null",当按wmosubregion字段聚合时,Geopandas会尝试把全球几乎所有国家的边界合并成一个超级大的多边形——这个计算量实在太大了,自然会卡住。
如果你的需求只是把这4个国家合并成EAST_AFRICA区域,同时保留其他国家的独立形状,那可以试试下面的优化方案:
1. 先优化赋值逻辑,用矢量化操作替代循环
你现在用循环逐行赋值的效率很低,换成Geopandas/Pandas的矢量化操作能快不少:
import geopandas as gpd import pandas as pd shape='/Volumes/TwoGb/shape/fwdshapfileoftheworld/' countries=gpd.read_file(shape+'TM_WORLD_BORDERS-0.3.shp') country_list=['SO','SD','DJ','KM'] default = 'Null' # 用矢量化方式赋值,替代循环 countries['wmosubregion'] = default countries.loc[countries.ISO2.isin(country_list), 'wmosubregion'] = "EAST_AFRICA"
2. 拆分聚合逻辑,避免合并巨型多边形
不要让dissolve处理所有国家,只对需要聚合的4个国家执行合并,再和其他国家拼接:
# 筛选出需要聚合的4个国家,单独执行dissolve east_africa_group = countries[countries.ISO2.isin(country_list)] east_africa_dissolved = east_africa_group.dissolve(by='wmosubregion') # 筛选出不需要聚合的其他国家 other_countries = countries[~countries.ISO2.isin(country_list)] # 把两部分结果合并起来 region_shapes = pd.concat([other_countries, east_africa_dissolved], ignore_index=True)
这样修改后,dissolve只需要处理4个国家的几何合并,计算量会大幅降低,应该能很快完成运行啦!
备注:内容来源于stack exchange,提问作者Kernel
相关产品推荐
相关产品推荐

