Randomize Coordinates within GeoDataFrame Bounds

  • Share this:

Code introduction


This function accepts a GeoDataFrame as input and generates a specified number of random points within the geometries' bounds of the input GeoDataFrame, then adds these points to the original GeoDataFrame.


Technology Stack : GeoPandas, NumPy

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import geopandas as gpd
import numpy as np

def randomize_coordinates(gdf, num_points=10):
    """
    This function adds random points within the bounds of a GeoDataFrame.
    
    Args:
        gdf (GeoDataFrame): The GeoDataFrame with geometries to create random points around.
        num_points (int): The number of random points to generate.

    Returns:
        GeoDataFrame: A new GeoDataFrame containing the original geometries and the random points.
    """
    random_points = gpd.GeoDataFrame({
        'geometry': [gdf.geometry.buffer(np.random.uniform(0, 0.1)) for _ in range(num_points)]
    })
    
    return gpd.GeoDataFrame(pd.concat([gdf, random_points])).reset_index(drop=True)