使用Python scipy interpolate.interpn值错误将带有规则网格的变量插入到不在常规网格上的位置

时间:2016-10-16 20:05:21

标签: python scipy interpolation

我有一个来自netcdf文件的变量,它是常规网格化数据的时间,高度,经度和纬度的函数:U [时间,高度,经度,纬度]。我想将此变量插入到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

1 个答案:

答案 0 :(得分:2)

您可以使用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)