【问题标题】:using numpy to get rid of a loop使用 numpy 摆脱循环
【发布时间】: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 来替换这个双循环,但我不知道从哪里开始

【问题讨论】:

    标签: python numpy matrix


    【解决方案1】:

    也许你可以看看 numpy meshgrid 功能。我不确定您的最终结果应该是什么样子,但您可以通过以下方式轻松找到 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.
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多