生成位于 geopandas 线串上的点
Generate points which lie on linestring in geopandas
假设我有以下地理数据框:
import geopandas as gpd
from shapely.geometry import LineString
line = LineString([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)])
gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[line])
现在我想要实现的是生成,比方说,100 个随机位于 gdf 中给定的线串上的点。然后创建另一个仅包含这些点的地理数据框。
可能吗?
最佳
- 很明显一个LineString有多个直线段
- 在每个线段上生成线性间隔的点
- 随机select沿每个线段生成的一些点
- 已使用 folium
进行可视化以使其清晰
import geopandas as gpd
from shapely.geometry import LineString, Point
import numpy as np
line = LineString([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)])
gdf = gpd.GeoDataFrame(index=[0], crs="epsg:4326", geometry=[line])
N_POINTS = 20
POINTS_PER_SEGMENT = 100
# generate points per segment and randomly select N of them
gdf2 = gpd.GeoDataFrame(
geometry=np.random.choice(
[
Point(x, y)
for p1, p2 in zip(line.coords, line.coords[1:]) # iterate through line segments
for x, y in zip(
np.linspace(p1[0], p2[0], POINTS_PER_SEGMENT),
np.linspace(p1[1], p2[1], POINTS_PER_SEGMENT),
)
],
N_POINTS,
),
crs="epsg:4386",
)
m = gdf.explore(color="red", height=300, width=500)
gdf2.explore(m=m)
假设我有以下地理数据框:
import geopandas as gpd
from shapely.geometry import LineString
line = LineString([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)])
gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[line])
现在我想要实现的是生成,比方说,100 个随机位于 gdf 中给定的线串上的点。然后创建另一个仅包含这些点的地理数据框。
可能吗?
最佳
- 很明显一个LineString有多个直线段
- 在每个线段上生成线性间隔的点
- 随机select沿每个线段生成的一些点
- 已使用 folium 进行可视化以使其清晰
import geopandas as gpd
from shapely.geometry import LineString, Point
import numpy as np
line = LineString([(2.2, 4.2), (7.2, -25.1), (9.26, -2.456)])
gdf = gpd.GeoDataFrame(index=[0], crs="epsg:4326", geometry=[line])
N_POINTS = 20
POINTS_PER_SEGMENT = 100
# generate points per segment and randomly select N of them
gdf2 = gpd.GeoDataFrame(
geometry=np.random.choice(
[
Point(x, y)
for p1, p2 in zip(line.coords, line.coords[1:]) # iterate through line segments
for x, y in zip(
np.linspace(p1[0], p2[0], POINTS_PER_SEGMENT),
np.linspace(p1[1], p2[1], POINTS_PER_SEGMENT),
)
],
N_POINTS,
),
crs="epsg:4386",
)
m = gdf.explore(color="red", height=300, width=500)
gdf2.explore(m=m)