![](/img/trans.png)
[英]Python: Efficiently interpolate from an irregular grid to a regular grid in 2D
[英]interpolate time series of 2d gridded data to a new 2d grid - efficiently
我有一個帶有時間軸的二維網格數據 numpy 數組,所以我的數組的形狀為 (nsteps, ny, nx)
對於上下文,它是地球的網格(x = 0 到 360,增量為 1 度,y = -90 到 90,增量為 1 度)。 在這個網格上的每個點都有時間序列的數據,每個時間步長 1 個數組。
我正在嘗試將數據從這個網格插入到一個非常不同的網格(不同的分辨率和節點點)。
我能夠通過以下方式做到這一點:
import numpy as np
from scipy.interpolate import RectBivariateSpline
from tqdm import tqdm
#interpolate the msl pressures back to the other grid
p_dat = pres[0].values #this is a numpy array (nsteps, ny0, nx0)
w_dat = wind[0].values #this is a numpy array (nsteps, ny1, nx1)
#new array with 2d shape of w_dat
out = np.full((p_dat.shape[0], *w_dat.shape[1:]), np.nan)
#interpolate one timestep at a time
for i in tqdm(list(range(out.shape[0]))):
interp = RectBivariateSpline(pres.geometry.y, pres.geometry.x, p_dat[i])
dat = interp(wind.geometry.y, wind.geometry.x)
out[i,:,:] = dat
有沒有辦法可以避免這個循環並將這個插值向量化到第 0 軸上?
您有任何數據可以添加到您的問題中嗎? 這將使我們能夠更仔細地觀察。
我認為np.apply_along_axis
可能在這里工作。
現在我只能提供這種未經測試的方法:
def helper(idx: int):
interp = RectBivariateSpline(pres.geometry.y, pres.geometry.x, p_dat[idx])
dat = interp(wind.geometry.y, wind.geometry.x)
return dat
out = np.apply_along_axis(helper, axis=0, arr=np.arange(out.shape[0]))
編輯:由於缺乏測試數據,我無法評論加速,但這與map(helper, np.arange(out.shape[0]))
非常相似。 本質上,它只是隱藏了循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.