Skip to content Skip to sidebar Skip to footer

St_make_grid Method Equivalent In Python

Is there an equivalent to the very good st_make_grid method of the sf package from r-spatial in python? The method create rectangular grid geometry over the bounding box of a polyg

Solution 1:

Would this be effective on many polygons to process?

Certainly not. There's no built-in Python version but the function below does the trick. If you need performance, make sure that you have pygeos installed in your environment.

def make_grid(polygon, edge_size):
    """
    polygon : shapely.geometry
    edge_size : length of the grid cell
    """
    from itertools import product
    import numpy as np
    import geopandas as gpd
    
    bounds = polygon.bounds
    x_coords = np.arange(bounds[0] + edge_size/2, bounds[2], edge_size)
    y_coords = np.arange(bounds[1] + edge_size/2, bounds[3], edge_size)
    combinations = np.array(list(product(x_coords, y_coords)))
    squares = gpd.points_from_xy(combinations[:, 0], combinations[:, 1]).buffer(edge_size / 2, cap_style=3)
    return gpd.GeoSeries(squares[squares.intersects(polygon)])

Post a Comment for "St_make_grid Method Equivalent In Python"