有没有一种快速的方法将点投影到特定的网格上?

2024-04-29 16:50:23 发布

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

我现在尝试将具有三维坐标(x,y,z)的n个点投影到具有特定大小(如64*64)的xy网格上,当然这n个点的坐标在此网格中受到限制

目标是打印投影到每个栅格元素上的点的z坐标。我写了两个for循环,但是有没有更好的方法来避免使用for循环来更快地运行它呢

for i in range(XY_grid.shape[0]):
    x = np.where((X_coordinate > i) & (X_coordinate <= i + 1), 1, 0)
    for j in range(XY_grid.shape[1]):
        y = np.where(( Y_coordinate > j) & (Y_coordinate <= j + 1), 1, 0)  
        print(x * y * Z_coordinate)

Tags: in网格元素coordinate目标fornprange
2条回答

我认为您需要的是二维直方图:

import numpy as np

# generate some data (x, y, z)
x = np.arange(100)
y = np.random.rand(100)
z = np.arange(100)[::-1] * 1.5

# grid (x, y) onto a defined grid (0-127) in x and y
grid, xe, ye = np.histogram2d(x, y, bins=(np.arange(128), np.arange(128)), weights=None)

grid.sum()
>>> 100.0 # all data is in the grid (was only 100 points)

您可以使用weight参数添加z值:

# grid (x, y) onto a defined grid (0-127) in x and y
grid, xe, ye = np.histogram2d(x, y, bins=(np.arange(128), np.arange(128)), weights=z)

grid.sum()
>>> 7425.0

z.sum()
>>> 7425.0 # all z values are in the produced grid

您可以更改bins宽度等,使其不均匀,或使其均匀分布在规则栅格中

生成的grid是一个2D numpy数组,其中包含落入每个bin的所有z信息。您可以轻松地print它或循环它以依次获得每个元素

要打印Z_coordinate中与X_coordinateY_coordinate中特定点相关的所有条目,可以执行以下操作:

for i in range(XY_grid.shape[0]):
    for j in range(XY_grid.shape[1]):
        print(Z_coordinate[np.logical_and(X_coordinate==i, Y_coordinate==j)])

相关问题 更多 >