如何解决使用 Geopandas 计算重叠特征
注意:我问过同样的问题 here,但到目前为止没有得到任何反馈。
有没有一种方法可以使用 Geopandas 轻松计算重叠多边形的数量,与 ArcGIS Pro Count Overlapping Features 的工作方式相同?
到目前为止,我的方法是先进行联合叠加,然后将 dissolve 与 aggfunc='count'
结合使用,但由于某种原因,我得到的结果不正确。
我在一个地理数据框中有 3 个重叠的多边形:
然后我进行叠加:
union = gpd.overlay(gdf,gdf,how='union')
结果我只得到 9 个多边形,虽然我应该得到 10 个(这是 QGIS 或 ArcGIS 中的 union
会返回的):
我的方法有什么问题吗?在单个地理数据框中计算重叠多边形的最佳方法是什么?
完整代码如下。它返回 9 个多边形。根据我对 union/intersect
操作的理解,它应该产生 10 个多边形。 3个多边形的交集只计算两次,而不是三次...QGIS中对同一组多边形的并集运算结果为10个多边形。
import pandas as pd
import matplotlib as plt
import geopandas as gpd
from shapely import wkt
data = {'name': ['polygon A','polygon B','polygon C'],'id': [1,2,3],'geom': ['MULTIPOLYGON (((36.00000 11.00000,36.00000 12.00000,37.00000 12.00000,37.00000 11.00000,36.00000 11.00000)))','MULTIPOLYGON (((36.50000 11.50000,37.50000 11.50000,37.50000 11.00000,36.50000 11.00000,36.50000 11.50000)))','MULTIPOLYGON (((36.61799 10.80580,36.61570 11.19321,36.86327 11.29637,37.34925 10.91813,37.00540 10.71182,36.61799 10.80580)))']
}
df = pd.DataFrame (data,columns = ['name','id','geom'])
df['geom'] = df['geom'].apply(wkt.loads)
gdf = gpd.GeoDataFrame(df,geometry='geom')
gdf.plot(alpha=0.5,column='id')
union = gpd.overlay(gdf,how='union')
len(union)
预期结果:
解决方法
如果您需要 ArcGIS Pro Count Overlapping Features 工具的计数和输出,这应该可以工作。如果要包含原始多边形,可以注释掉/删除此行:other_poly_list.remove(idx)。
intersection_polygons_list = []
for idx,row in gdf.iterrows():
main_poly_gdf = gdf.iloc[idx:idx+1,:]
print('\n' + 'main poly:',main_poly_gdf['id'].tolist()[:])
other_poly_list = gdf.index.tolist()
other_poly_list.remove(idx)
other_poly_gdf = gdf[gdf.index.isin(other_poly_list)]
print('other polys:',other_poly_gdf['id'].values.tolist()[:])
intersection_polygons = gpd.overlay(main_poly_gdf,other_poly_gdf,how='intersection')
intersection_polygons_list.append(intersection_polygons)
intersections_gdf = pd.concat(intersection_polygons_list)
intersections_gdf_gb = intersections_gdf.groupby('name_1').agg({'name_2':'size'})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。