Python >> Tutoriel Python >  >> Python Tag >> Pandas

Création d'une grille de polygones à l'aide de Geopandas

La réponse précédente donne un résultat correct, mais je me suis permis d'améliorer le code, d'éviter de nombreuses lignes inutiles, ainsi que d'itérer sur les index au lieu des valeurs de la liste.

import geopandas as gpd
from shapely.geometry import Polygon
import numpy as np
points = gpd.read_file('points.shp')

xmin,ymin,xmax,ymax = points.total_bounds

length = 1000
wide = 1200

cols = list(range(int(np.floor(xmin)), int(np.ceil(xmax)), wide))
rows = list(range(int(np.floor(ymin)), int(np.ceil(ymax)), length))
rows.reverse()

polygons = []
for x in cols:
    for y in rows:
        polygons.append( Polygon([(x,y), (x+wide, y), (x+wide, y-length), (x, y-length)]) )

grid = gpd.GeoDataFrame({'geometry':polygons})
grid.to_file("grid.shp")

L'idée principale est peut-être la même, mais nous créons maintenant beaucoup moins de variables inutiles et l'ensemble du code est plus clair à comprendre


Il existe de nombreuses solutions.

L'un d'eux

 import geopandas as gpd
 from shapely.geometry import Polygon
 import numpy as np
 points = gpd.read_file('points.shp')
 xmin,ymin,xmax,ymax =  points.total_bounds
 width = 2000
 height = 1000
 rows = int(np.ceil((ymax-ymin) /  height))
 cols = int(np.ceil((xmax-xmin) / width))
 XleftOrigin = xmin
 XrightOrigin = xmin + width
 YtopOrigin = ymax
 YbottomOrigin = ymax- height
 polygons = []
 for i in range(cols):
    Ytop = YtopOrigin
    Ybottom =YbottomOrigin
    for j in range(rows):
        polygons.append(Polygon([(XleftOrigin, Ytop), (XrightOrigin, Ytop), (XrightOrigin, Ybottom), (XleftOrigin, Ybottom)])) 
        Ytop = Ytop - height
        Ybottom = Ybottom - height
    XleftOrigin = XleftOrigin + width
    XrightOrigin = XrightOrigin + width

grid = gpd.GeoDataFrame({'geometry':polygons})
grid.to_file("grid.shp")

Vous pouvez aussi tronquer la grille (coque convexe) :

Mais l'un des plus intéressants est d'utiliser le module gpd_lite_toolboox)