如何展平三个独立的二维数组,同时保持点相关性?例如,我正在从包含 x 和 y 位置信息以及一些相关数据数组 (cartm) 的数据集创建网格。插值后,由于网格的原因,X2
和 Y2
的大小为 300x300; interpval
的大小也为 300x300,因为每个 interpval
点都与 (X2,Y2) 网格上的单个坐标相关。
如何展平这些二维矩阵中的每一个,并保持 interpval
值与其在网格网格上的位置之间的 1:1 相关性?最终,我希望得到一个 Nx3 数组,其中包含一个 X 位置列、一个 Y 位置列和一个包含相应插值数据的列。提前致谢!
import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt
# Create x,y vectors
cartx = np.array([0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
carty = np.array([1, 23, 4, 6, 12, 15, 16, 18, 20, 21, 22])
# Create data vector
cartm = np.array([5.3, 23, 2, 5, 2, 2.5, 13, 9, 7.5, 1.7, 12])
# Prepare meshgrid, interpolate
cartcoord = zip(cartx, carty)
X = np.linspace(cartx.min(), cartx.max(), 300)
Y = np.linspace(carty.min(), carty.max(), 300)
X2, Y2 = np.meshgrid(X, Y)
interp = scipy.interpolate.LinearNDInterpolator(cartcoord, cartm, fill_value=0)
interpval = interp(X2, Y2)
print(X2.shape, Y2.shape, interpval.shape)
最佳答案
您可以使用ravel()
展平X2
、Y2
和interpval
的方法。要将它们放入 Nx3 数组中,可以使用 numpy.column_stack
。所以
这应该可以做到:
np.column_stack((X2.ravel(), Y2.ravel(), interpval.ravel()))
例如,
In [91]: X2
Out[91]:
array([[1, 2],
[3, 4]])
In [92]: Y2
Out[92]:
array([[11, 12],
[13, 14]])
In [93]: Z2
Out[93]:
array([[21, 22],
[23, 24]])
In [94]: np.column_stack((X2.ravel(), Y2.ravel(), Z2.ravel()))
Out[94]:
array([[ 1, 11, 21],
[ 2, 12, 22],
[ 3, 13, 23],
[ 4, 14, 24]])
关于arrays - 保持点相关性,同时展平二维网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36337701/