使用Python的scipy interpolate.interpn value error将具有规则网格的变量插入到非



我有一个来自netcdf文件的变量,它是规则网格数据的时间,高度,lon和lat的函数:U[时间,高度,lon,lat]。我想将这个变量插入到一个定义的位置lon_new,lat_new,这个位置不在常规网格上(它在网格点之间)。我希望变量U[0,0,lon_new,lat_new]能够在单个插值位置中得到。

我阅读了scipy插值函数,并认为scipy.interpolate.interpn是我想使用的函数。我试图做这个函数的一个简单的例子,但不断得到一个错误。

x_points = [1,2,3,4] #lets call this list of lons on the grid
y_points = [1,2,3,4] #lets call this list of lats on the grid
#Get the lon,lat pairs
point_pairs=[]
for i in x_points:
    for j in y_points:
        points = [i,j]
        point_pairs.append(points)
print point_pairs
print np.shape(point_pairs)
[[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3,  2], [3, 3], [3, 4], [4, 1], [4, 2], [4, 3], [4, 4]]
(16L, 2L)
xi = (2.5,2.5) #point in between grid points that I am interested in getting     the interpolated value
xi=np.array(xi)
print xi
print np.shape(xi)
[ 2.5  2.5]
(2L,)
values = np.ones(16) #array of values at every grid point Let's say I loop   over every grid point and get the value at each one
print values
[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
interpolated_value = interpolate.interpn(point_pairs, values, xi, method='linear')
ValueError: There are 16 point arrays, but values has 1 dimensions

您可以使用scipy中的任何合适的多元插值函数。通过以下更正,您的示例将产生正确的结果。

# -*- coding: utf-8 -*-
import numpy as np
from scipy import interpolate
x_points = np.array([1, 2, 3, 4])
y_points = np.array([1, 2, 3, 4])
values = np.ones((4, 4))   # 2 dimensional array
xi = np.array([2.5, 2.5])
interpolated_value = interpolate.interpn((x_points, y_points), values, xi, method='linear')
print(interpolated_value)

最新更新