【发布时间】:2019-08-23 12:04:47
【问题描述】:
我正在寻找一种使用 numpy 将双循环替换为矩阵运算的方法。我有一个代表正方形四个节点的坐标列表。 如[(0,0),(0,1),(1,1),(1,0)]。从那个正方形我想制作一个 10 x 10 正方形的网格。
我不知道如何使用 numpy 来实现。所以我改用循环。
使用 shapely 将坐标序列转换为 #geopandas 的对象
from shapely.geometry import Polygon
import numpy as np
# coordinate defining the size of the grid
xmin, ymin, xmax, ymax = [0, 0, 10, 10]
# defining the size of the basic square of the grid
height = 10
width = 10
# counting number of squares the function has to make to create the grid
rows = int(np.ceil((ymax - ymin) / height))
cols = int(np.ceil((xmax - xmin) / width))
# coordinates of the first square
XleftOrigin = xmin
XrightOrigin = xmin + width
YtopOrigin = ymax
YbottomOrigin = ymax - height
# making to list to keep track of the squares and id of the square
polygons = []
p_id = []
cpt = 0
# looping over cols and rows to generate every square of the grid by #translating the coordinate of the first square
for i in range(0,cols):
Ytop = YtopOrigin
Ybottom = YbottomOrigin
for j in range(0,rows):
polygons.append(Polygon([(XleftOrigin, Ytop), (XrightOrigin, Ytop), (XrightOrigin, Ybottom), (XleftOrigin, Ybottom)]))
p_id.append(str(cpt))
cpt += 1
Ytop = Ytop - height
Ybottom = Ybottom - height
XleftOrigin = XleftOrigin + width
XrightOrigin = XrightOrigin + width
我想用 numpy 来替换这个双循环,但我不知道从哪里开始
【问题讨论】: