我刚开始使用geopandas
,所以我有一个很基本的问题。我想确定地理数据框中相邻位置之间发生了联系边界。
我将提供一个示例。以下代码在预加载的地理框中读取内容,随机创建标记为“已处理”的国家/地区,定义一个为其邻国提供功能的函数,然后将结果与边界略浅的国家/地区绘制成图形。
import geopandas as gp
import numpy as np
import matplotlib.pyplot as plt
path = gp.datasets.get_path('naturalearth_lowres')
earth = gp.read_file(path)
africa = earth[earth.continent=='Africa']
africa['some_places'] = np.random.randint(0,2,size=africa.shape[0])*2
# Define and apply a function that determines which countries touch which others
def touches(x):
result = 0
if x in africa.loc[africa.some_places==2,'geometry']:
result = 2
else:
for y in africa.loc[africa.some_places==2,'geometry']:
if y.touches(x) :
result = 1
break
else:
continue
return result
africa['touch'] = africa.geometry.apply(touches)
# Plot the main places which are 2, the ones that touch which are 1, and the non-touching 0
fig, ax = plt.subplots()
africa.plot(column='touch', cmap='Blues', linewidth=0.5, ax=ax, edgecolor='.2')
ax.axis('off')
plt.show()
对我来说,它给出了以下地图:
现在的问题是,我实际上不希望所有区域都被淡蓝色阴影。我(理想情况下)是要确定沿治疗国家的边界的长度,然后根据与一个或多个受治疗国家共享的边界数量来确定您所受影响的程度。 >
至少,我希望能够扔掉与另一个国家仅相距1或2英里边界(或可能在某个角落相遇)的地方。欢迎任何建议或解决方案!
答案 0 :(得分:1)
我认为您需要一个示例来演示正确的地理空间操作以获取结果。下面的代码显示了如何在北美和南美大陆之间进行intersection
,获取相交线,然后计算其长度。最后,在地图上画线。我希望它对您的项目有用并能适应您的项目。
import geopandas
import numpy as np
import matplotlib.pyplot as plt
# make use of the provided world dataset
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
# drop some areas (they crash my program)
world = world[(world.name != "Antarctica") & (world.name != "Fr. S. Antarctic Lands")]
# create a geodataframe `wg`, taking a few columns of data
wg = world[['continent', 'geometry', 'pop_est']]
# create a geodataframe `continents`, as a result of dissolving countries into continents
continents = wg.dissolve(by='continent')
# epsg:3857, Spherical Mercator
# reproject to `Spherical Mercator` projection
continents3857 = continents.to_crs(epsg='3857')
# get the geometry of the places of interest
namerica = continents3857.geometry[3] # north-america
samerica = continents3857.geometry[5] # south-america
# get intersection between N and S America continents
na_intersect_sa = namerica.intersection(samerica) # got multi-line
# show the length of the result (multi-line object)
blength = na_intersect_sa.length # unit is meters on Spherical Mercator
print("Length in meters:", "%d" % blength)
# The output:
# Length in meters: 225030
ax = continents3857.plot(column="pop_est", cmap="Accent", figsize=(8,5))
for ea in na_intersect_sa.__geo_interface__['coordinates']:
#print(ea)
ax.plot(np.array(ea)[:,0], np.array(ea)[:,1], linewidth=3, color="red")
ax.set_xlim(-9500000,-7900000)
ax.set_ylim(700000, 1400000)
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
rect = plt.Rectangle((xmin,ymin), xmax-xmin, ymax-ymin, facecolor="lightblue", zorder=-10)
ax.add_artist(rect)
plt.show() # sometimes not needed
结果图: