You can download this code by clicking the button below.
This code is now available for download.
This function takes a GeoDataFrame containing polygons and returns a new GeoDataFrame with the coordinates of the polygons randomized within a certain range.
Technology Stack : GeoPandas, Pandas, NumPy, Matplotlib
Code Type : Function
Code Difficulty : Intermediate
import geopandas as gpd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def randomize_polygon_coordinates(polygon):
"""
This function takes a GeoDataFrame with polygons and returns a new GeoDataFrame with the coordinates of the polygons randomized within a certain range.
"""
def randomize_coordinates(row):
# Get the polygon coordinates
x_coords, y_coords = zip(*row['geometry'].exterior.coords)
# Randomize the x and y coordinates within a range of 0.1
x_coords = [x + np.random.uniform(-0.1, 0.1) for x in x_coords]
y_coords = [y + np.random.uniform(-0.1, 0.1) for y in y_coords]
# Create a new Polygon with randomized coordinates
return gpd.Polygon([[x, y] for x, y in zip(x_coords, y_coords)])
# Apply the randomize_coordinates function to each row of the GeoDataFrame
polygon['geometry'] = polygon.apply(randomize_coordinates, axis=1)
return polygon
# Example usage:
# Load a GeoDataFrame
gdf = gpd.read_file('path_to_shapefile.shp')
# Randomize the coordinates of the polygons
randomized_gdf = randomize_polygon_coordinates(gdf)