在展平 2D 网格时保持点相关性

Maintaining point correlation while flattening 2D meshgrid

如何展平三个独立的二维数组,同时保持点相关性?例如,我正在从包含 x 和 y 的位置信息以及一些相关数据数组 (cartm) 的数据集中创建网格。插值后,X2Y2 由于网格的原因,大小为 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() method to flatten X2, Y2 and interpval. To put them into an Nx3 array, you can use 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]])