【问题标题】:geopandas color closest shapes the same colorgeopandas 颜色最接近的形状相同的颜色
【发布时间】:2019-01-30 21:05:41
【问题描述】:
我有一个 geopandas 文件,其中包含 100 多个多边形和一个稀疏集(其中约 10 个)具有感兴趣的值。我有没有一种简单的方法可以根据最近的非零多边形的值为剩余的 90 多个多边形分配一个值?
提前谢谢你
【问题讨论】:
标签:
python
geospatial
polygon
geopandas
【解决方案1】:
下面的代码表示一种算法,该算法将使用基于质心的空间连接(最近邻)将“无值”多边形与具有有效值的最近多边形连接起来。
请注意,代码是您需要的代码草稿;它表示一般算法,但您需要根据您的数据和变量完成功能。
# gdf with all the polygons
gdf1 = gpd.read_file(...)
# calculate a column with the centroid geometry;
# it will be used later.
# note: this is not the active gdf geometry at this stage
gdf1['geometry_pt'] = gdf1['geometry'].centroid
# set the point geometry as the active geometry
gdf1.set_geometry('geometry_pt')
# filter out the gdf in two gdfs, with/without the value you want
gdf1_yesval = gdf1.loc[gdf1['field1'] != 0]
gdf1_noval = gdf1.loc[gdf1['field1'] == 0]
# perform a spatial join to assign the closest value to the points with no value
# for this, apply the code in the link below
gdf1_noval_joined = gdf1_noval.apply(... nearest... gdf1_yesval... )
# do the necessary column operations in the joined gdf
# to update your desired columns with values from the spatially joined gdf
gdf1_noval_joined['field1'] = gdf1_noval_joined['joinedfieldA']
# delete the unnecessary columns in the joined gdf
gdf1_noval_joined.drop(columns=['joinedfieldA', 'joinedfieldB'], inplace=True)
# concatenate the two gdfs to make one
df2 = pd.concat([gdf1_yesval, gdf1_noval_joined])
# convert it into a gdf again
gdf2 = gpd.GeoDataFrame(df2, geometry='geometry')
最近邻连接函数的解释链接是:https://gis.stackexchange.com/q/222315/93912
希望对你有帮助。