Reputation: 453
Lets say that I have the following geodataframe:
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])
Now what I want to achieve is to generate, lets say, 100 points that randomly lie on this linestring given in gdf. And then create another geodataframe which only includes these points.
Is it possible?
Best
Upvotes: 0
Views: 2021
Reputation: 31166
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)
Upvotes: 1