有没有比 np.where 更好的方法来使用条件语句索引大型数组?

Is there a better way to index a large array using a conditional statement than np.where?

对不起,文字墙。我试图缩短它,但我认为所有内容都会对愿意阅读所有内容的人有所帮助。

我有 xyz 点云,我正在尝试将它们网格化为 DEM(如果您不熟悉,则为数字高程模型 - 只是 2D 高程阵列)。我的 DEM 需要具有比我的点云低得多的分辨率(相反,它们不需要几乎和我的点云一样高的分辨率),因此我的点云中每个 DEM 单元格大约有 10 个点。我的代码遍历最终 DEM 的行和列,并根据提供的 XYZ 坐标计算每个单元格的高程值。为此,我指定了网格大小和间距,然后代码计算每个网格单元的 x 和 y 最大值和最小值。然后,它找到 z 所有 z 值,其中 x 和 y 在该单元格的最大值和最小值范围内,拒绝异常值并取剩余值的平均值以确定该单元格的最终值。 xyz 值存储在如下所示的数组中:

xyz = np.array([[x1, y1, z1],
                [x2, y2, z2],
                [x3, y3, z3]])       #     with tens of thousands of xyz cominations

我当前的方法涉及创建 X 和 Y 中的像元边界值列表,然后将边界内具有 x 和 y 值的所有 z 值添加到高程列表中:

dx = 0.5           # cell size in meters

xmin = np.min(xyz[:,0])
xmax = np.max(xyz[:,0])
ymin = np.min(xyz[:,1])
ymax = np.max(xyz[:,1])
xoffset = ((xmax-xmin) % dx)/2.0
yoffset = ((ymax-ymin) % dx)/2.0


xlims = np.arange(xmin+xoffset, xmax, dx)   # list of grid cell limits in x
ylims = np.arange(ymin+yoffset, ymax, dx)   # list of grid cell limits in y

DEM = np.empty((len(ylims)-1, len(xlims)-1), 'float')  # declares output array

for i in range(DEM.shape[0]):           # iterate over rows of final DEM
    for j in range(DEM.shape[1]):       # iterate over columns of final DEM
        bottom = ylims[i]               
        top = ylims[i+1]                
        left = xlims[j]                 # these rows just pick minimum and
        right = xlims[j+1]              # maximum of cell [i,j]

        elevations = xyz[np.where(((xyz[:,0] > left) &
                            (xyz[:,0] < right)) & 
                            ((xyz[:,1] > bottom) & 
                            (xyz[:,1] < top)))[0]][:,2]
        elevations = reject_outliers(elevations)

        if len(elevations) == 0:
            elevation = np.nan
        else:
            elevation = np.mean(elevations)

        DEM[i,j] = elevation

这行得通,但我必须做数百个 DEM,每个都有数十万个点,所以如果我这样做的话,我要等一周才能让我的计算机通电.这对我来说也很笨重。有没有办法简化这个?

你可以试试

elev =  xyz[  xyz[:,0] > left  ]
elev = elev[ elev[:,0] < right ]
elev = elev[ elev[:,1] > bottom]
elev = elev[ elev[:,1] < top   ]

这样,每个条件语句都减少了elev的大小,因此每个下一个条件语句要考虑的对象就更少了。我仍然怀疑有更好的方法。您还可以尝试从 xyz 搜索最近的 x,y 到 xlimsylims 的 x,y,然后使用 dxdy。如果你能找到一种快速搜索的方法,那么这可能是你最好的选择(但在接近边界时你需要小心

一边

如果 xyz 中的 x,y 形成规则的细网格,您可以尝试 scipy.interpolate.RectBivariateSpline

否则你可以使用scipy.interpolate.interp2d:

from scipy.interpolate import interp2d

interped = interp2d( x=xyz[:,0], y=xyz[:,1], z=xyz[:,2], kind='linear', fill_value=xyz[:,2].mean() )
DEM     = interped( xlims, ylims)

(它会比 RectBivariateSpline 慢很多,但可能比你正在做的更快)

您可以将 'kind' 参数更改为 'cubic',但它会变慢。

一种可能性是找到这些点适合的段,然后循环遍历这些组,这样您就不必一直屏蔽相同的元素,即使它们只属于一个段。

一种方法是使用 numpy 的内置 searchsorted:

xmin = np.min(xyz[:,0])
xmax = np.max(xyz[:,0])
ymin = np.min(xyz[:,1])
ymax = np.max(xyz[:,1])
xoffset = ((xmax-xmin) % dx)/2.0
yoffset = ((ymax-ymin) % dx)/2.0

xlims = np.arange(xmin+xoffset, xmax, dx)   # list of grid cell limits in x
ylims = np.arange(ymin+yoffset, ymax, dx)   # list of grid cell limits in y

DEM = np.empty((len(ylims) - 1, len(xlims) - 1), dtype=float)  # declares output array

# Find the bins that each point fit into
x_bins = np.searchsorted(xlims, xyz[:, 0]) - 1
y_bins = np.searchsorted(ylims, xyz[:, 1]) - 1

for i in range(DEM.shape[0]):           # iterate over rows of final DEM
    y_mask = y_bins == i
    for j in range(DEM.shape[1]):
        elevations = xyz[y_mask & (x_bins == j), 2]
        elevations = reject_outliers(elevations)
        if len(elevations) == 0:
            elevations = np.nan
        else:
            elevations = np.mean(elevations)

        DEM[i, j] = elevations

当我使用 timeit 和 xyz = randn(100000, 3) 和 dx = 0.1 分析已经列出的备选方案时(在将 reject_outliers 定义为 lambda x: x 之后),我得到了以下时间:

  1. (your) where 方法:10 次循环,最好的 3 次:每次循环 6.69 秒
  2. (dermon's) 逐步方法:10 次循环,最好的 3 次:每次循环 16.7 秒
  3. searchsorted 方法:10 次循环,3 次最佳:每次循环 2.11 秒

但是,如果您愿意使用 Pandas,您可以修改代码,将双 for 循环替换为 Pandas 很棒的 groupby 功能:

elevation_df = pd.DataFrame({'x_bins': x_bins, 'y_bins': y_bins, 'z': xyz[:, 2]})
for x_y_bins, data in elevation_df.groupby(['x_bins', 'y_bins']):
    elevations = reject_outliers(data['z'])
    elevations = data['z']
    if len(elevations) == 0:
        elevations = np.nan
    else:
        elevations = np.mean(elevations)
    if 0 <= x_y_bins[1] < DEM.shape[0] and 0 <= x_y_bins[0] < DEM.shape[1]: 
        DEM[x_y_bins[1], x_y_bins[0]] = elevations

这将时间缩短了几乎 2 倍(10 次循环,最好的 3 次:每次循环 1.11 秒)。

我还应该注意到,由于您的 np.arange 命令,您似乎已经排除了范围内的一些点。在上面我假设你打算排除这些点,但如果你想包括你可以使用的所有数据:

xlims = np.arange(xmin-xoffset, xmax+dx, dx)
ylims = np.arange(ymin-yoffset, ymax+dx, dx)

如果您改用这些范围,您可以将我之前的 for 循环修改为:

for i in np.unique(y_bins):
    y_mask = y_bins == i
    for j in np.unique(x_bins[y_mask]):

将我之前的 searchsorted 示例的 timeit 结果降低到 10 个循环,最好的 3 个循环:每个循环 1.56 s 这至少更接近 Pandas groupby .