使用numpy消除循环

2024-10-08 19:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来取代一个双循环成一个矩阵运算使用numpy。我有一个代表正方形四个节点的坐标表。 例如[(0,0),(0,1),(1,1),(1,0)]。从那个正方形我想做一个10乘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来取代这个双循环,但我不知道从哪里开始


Tags: ofthetonumpynpwidthgridxmin
1条回答
网友
1楼 · 发布于 2024-10-08 19:18:51

也许你可以看看NumpyMeshGrid的功能。我不确定您的最终结果应该是什么样子,但通过以下方式,您可以轻松找到x点和y点的所有坐标:

import numpy as np


xmin, ymin, xmax, ymax = [0., 0., 200., 200.]

# 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))

# linspace gives a vector of a number of pieces between min and max
x = np.linspace(xmin, xmax, cols+1)
y = np.linspace(ymin, ymax, rows+1) # the +1 because of an "added border" instead of counting the squares, the corners are one point more

x_mat, y_mat = np.meshgrid(x, y) # here are 2 lists of lists corresponding to the lengths of x and y given.

相关问题 更多 >

    热门问题