我试图使用interp2D函数并循环遍历各层,但似乎f仅适用于i0的最后一个值。你正在每次迭代for循环时覆盖插值器f的值,因此当您完成对i0值的循环时,f将仅对应于data的最后一个Z平面。使用您当前的方法,您需要在for循环内调用f,例如:
N = 64
data = np.random.randn(10, 21, N)
X = np.linspace(10., 15., 21)
Y = np.linspace(0.05, 1.85, 10)
Xnew = np.linspace(10., 15., 41)
Ynew = np.linspace(0.05, 1.85, 20)
datanew = np.empty((Ynew.shape[0], Xnew.shape[0], N), data.dtype)
for i0 in np.arange(N):
f = interpolate.interp2d(X, Y, data[:,:,i0], kind='linear')
datanew[:,:,i0] = f(Xnew,Ynew)
您可以通过同时插值所有Z平面来消除
for
循环。一种方法是使用
scipy.interpolate.RegularGridInterpolator
:
from scipy.interpolate import RegularGridInterpolator
Z = np.arange(N)
itp = RegularGridInterpolator((Y, X, Z), data, method='linear')
grid = np.ix_(Ynew, Xnew, Z)
datanew2 = itp(grid)
在这里,我还使用np.ix_
构建一个“开放网格”,从您想要进行插值的坐标中插值data
。