我有 3D 数据。我想逐层(在 X、Y 平面中)插入此数据,因为计算每一层都需要很多时间。
我尝试使用 interp2D 函数并循环遍历各层,但 f 似乎仅适用于 i0 的最后一个值。
X = np.linspace(10., 15., 21)
Y = np.linspace(0.05, 1.85, 10)
for i0 in np.arange(N):
f = interpolate.interp2d(X, Y, data[:,:,i0], kind='linear')
Xnew = np.linspace(10., 15., 41)
Ynew = np.linspace(0.05, 1.85, 20)
datanew = f(Xnew,Ynew)
如何对数据的每一层进行插值?
谢谢
最佳答案
I try to use the interp2D function and loop through the layers but f seems to apply only to the last value of i0.
在 for
循环的每次迭代中,您都在覆盖插值 f
的值,因此当您完成对 i0< 的循环时
值 f
将仅对应于 data
的最后一个 Z 平面。使用您当前的方法,您需要在 for
循环中调用 f
,例如:
# some example data for test purposes
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)
# initialize output array
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')
# fill in this Z-slice
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
的坐标构建“开放网格”。
关于python - Python 中的 3D 数据插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34590430/