Randomly Adding Points to GeoDataFrame

  • Share this:

Code introduction


This function randomly selects coordinates from the input GeoDataFrame and adds these points to the GeoDataFrame.


Technology Stack : GeoPandas, NumPy

Code Type : Geographic data processing

Code Difficulty : Intermediate


                
                    
import geopandas as gpd
import numpy as np

def randomize_coordinates(geodataframe, num_points=10):
    """
    Randomly add new points to the GeoDataFrame at random coordinates within the existing geometry bounds.
    """
    # Create a GeoDataFrame with random points within the bounds of the input GeoDataFrame
    bounds = geodataframe.total_bounds
    random_points = gpd.points_from_bounds(*bounds, num_points=num_points)
    
    # Add the random points to the original GeoDataFrame
    geodataframe_with_random_points = geodataframe.copy()
    geodataframe_with_random_points = geodataframe_with_random_points.append(random_points, ignore_index=True)
    
    return geodataframe_with_random_points