【发布时间】:2013-08-17 16:09:39
【问题描述】:
假设我有三个任意一维数组,例如:
x_p = np.array((1.0, 2.0, 3.0, 4.0, 5.0))
y_p = np.array((2.0, 3.0, 4.0))
z_p = np.array((8.0, 9.0))
这三个数组表示 3D 网格中的采样间隔,我想为所有交叉点构造一个 3D 向量的 1D 数组,类似于
points = np.array([[1.0, 2.0, 8.0],
[1.0, 2.0, 9.0],
[1.0, 3.0, 8.0],
...
[5.0, 4.0, 9.0]])
顺序实际上并不重要。生成它们的明显方法:
npoints = len(x_p) * len(y_p) * len(z_p)
points = np.zeros((npoints, 3))
i = 0
for x in x_p:
for y in y_p:
for z in z_p:
points[i, :] = (x, y, z)
i += 1
所以问题是......有没有更快的方法?我已查看但未找到(可能只是未能找到正确的 Google 关键字)。
我目前正在使用这个:
npoints = len(x_p) * len(y_p) * len(z_p)
points = np.zeros((npoints, 3))
i = 0
nz = len(z_p)
for x in x_p:
for y in y_p:
points[i:i+nz, 0] = x
points[i:i+nz, 1] = y
points[i:i+nz, 2] = z_p
i += nz
但我觉得我错过了一些巧妙的 Numpy 方式?
【问题讨论】:
-
此问题已被标记为重复;这是一个类似的问题,但是(显然我有偏见)我认为我的问题是对更普遍问题的更简单的措辞。我也认为这个问题的答案更好;使用 meshgrid 似乎是最简单、最快的解决方案。
-
另外,在我看来,从 2D 到 3D 的扩展并不明显。看到答案具有相似的结构意味着直接扩展是一个好的开始,但是,先验,不清楚这些是否会起作用。
标签: python arrays performance numpy