Skip to main content
 首页 » 编程设计

python之在 python 中使用网格数据进行线性插值

2025年05月04日16kerrycode

我有一个维度为 33 X 77 X 77 的网格化天气数据集。第一个维度是时间,其余维度分别是纬度和经度。我需要每次将数据插值(线性或最近邻)到不同的点(纬度和经度)并将其写入 csv 文件。我使用了 scipy 中的 interp2d 函数,它在一个时间步内是成功的。因为我有很多位置,所以我不想随时间循环。

下面显示的是我写的一段代码,谁能建议一个更好的方法来完成任务?

import sys ; import numpy as np ; import scipy as sp ; from scipy.interpolate import interp2d ;import datetime ; import time ; import pygrib as pg ;  
grb_f=pg.open('20150331/gfs.20150331.grb2')  lat=tmp[0].data(lat1=4,lat2=42,lon1=64,lon2=102)[1] ; lat=lat[:,0];  
lon=tmp[0].data(lat1=4,lat2=42,lon1=64,lon2=102)[2] ; lon=lon[0,:] ;  
temp=np.empty((0,lon.shape[0])) 
for i in range(0,tmp.shape[0]): 
    dat=tmp[i].data(lat1=4,lat2=42,lon1=64,lon2=102) 
    temp=np.concatenate([temp,dat[0]-273.15],axis=0) 
temp1=temp.reshape(tmp.shape[0],lat.shape[0],lon.shape[0]) 
x=77 ; y=28 #(many points)  
f=interp2d(lon,lat, temp1[0,:,:],kind='linear',copy=False,bounds_error=True ) ; Z=f(x,y)   

编辑::

我没有制作 3D 矩阵,而是垂直附加数据并制作大小为 2541 X 77 和经纬度为 2541 X 1 的数据矩阵。interp2d 函数给出无效长度错误。

f=interp2d(lon,lat, temp1[0,:,:],kind='linear',copy=False,bounds_error=True ) 

"Invalid length for input z for non rectangular grid")

ValueError:非矩形网格的输入 z 长度无效

我的 x、y、z 矩阵的长度相同 (2541,2541,2541)。那为什么会抛出错误呢? 谁能解释一下?非常感谢您的帮助。

请您参考如下方法:

使用RedBlackPy 处理时间序列非常容易.

 import datetime as dt 
 import redblackpy as rb 
 
 index = [dt.date(2018,1,1), dt.date(2018,1,3), dt.date(2018,1,5)] 
 lat = [10.0, 30.0, 50.0] 
 # create Series object 
 lat_series = rb.Series(index=index, values=lat, dtype='float32', 
                        interpolate='linear') 
 # Now you can access at any key using linear interpolation 
 # Interpolation does not create new items in Series 
 # It uses neighbours to calculate value inplace when you call getitem 
 print(lat_series[dt.date(2018,1,2)]) #prints 20 

因此,如果您只想将插值写入 csv 文件,您可以遍历所需键的列表并调用 Series 对象的 getitem,然后将值写入文件:

 # generator for dates range 
 def date_range(start, stop, step=dt.timedelta(1)): 
 
     it = start - step 
 
     while it < step: 
         it += step 
         yield it 
 
 #------------------------------------------------ 
 # create list for keeping output strings 
 out_data = []     
 # create output file 
 out_file = open('data.csv', 'w') 
 # add head for output table 
 out_data.append('Time,Lat\n') 
 
 for date in date_range(dt.date(2018,1,1), dt.date(2018,1,5)): 
     out_data.append( '{:},{:}\n'.format(date, lat_series[date]) ) 
 
 # write output Series 
 out_file.writelines(out_data) 
 out_file.close() 

通过同样的方式,您可以添加到您处理的 Lon 数据。