You can download this code by clicking the button below.
This code is now available for download.
This custom function generates a specified number of random points within the polygons of a given GeoDataFrame.
Technology Stack : GeoPandas, NumPy
Code Type : Custom function
Code Difficulty : Intermediate
import geopandas as gpd
import numpy as np
def random_point_in_polygon(gdf, num_points=1):
"""
Generate random points within polygons.
Parameters:
gdf (GeoDataFrame): A GeoDataFrame with Polygon geometry.
num_points (int): Number of random points to generate. Default is 1.
Returns:
GeoDataFrame: A GeoDataFrame with the generated points.
"""
random_points = []
for idx, row in gdf.iterrows():
polygon = row.geometry
random_point = polygon.buffer(0).intersection(np.random.rand(1, 2) * polygon.bounds)
random_points.append(random_point)
return gpd.GeoDataFrame(random_points, geometry=True)