Skip to content

Instantly share code, notes, and snippets.

@lucgiffon
Created March 8, 2023 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucgiffon/3a3bbeaa50d1250d78c0f0d31512e12f to your computer and use it in GitHub Desktop.
Save lucgiffon/3a3bbeaa50d1250d78c0f0d31512e12f to your computer and use it in GitHub Desktop.
Generate random element in geoseries polygon Python
import random
from shapely.geometry import Point
def generate_random(number: int, polygon: gpd.GeoSeries):
"""
Select random point in polygon based on an inscribed circle of the polygon.
Parameters
----------
number
Number of random points
polygon
Geoseries
Returns
-------
List of shapely.geometry.Point objects
"""
cx = polygon.representative_point().x
cy = polygon.representative_point().y
dist_to_repr = polygon.exterior.distance(polygon.representative_point())
points = []
while len(points) < number:
r = dist_to_repr * 0.5 * np.sqrt(random.random())
theta = random.random() * 2 * np.pi
x = cx + r * np.cos(theta)
y = cy + r * np.sin(theta)
pnt = Point(x, y)
if polygon.contains(pnt).values[0]:
points.append(pnt)
return points
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment