在scipy.interpolate.griddata和method = nearest的边界之外使用fill_value

Arc*_*s B 2 python interpolation numpy scipy qhull

函数scipy.interpolate.griddata允许指定fill_valuedoc指出的关键字:

用于填写输入点凸包之外的请求点的值。如果未提供,则默认值为nan。 此选项对“最近”方法无效。

但是,fill_valuemethod='nearest'与2D数据一起使用时,我需要指定a 在边界之外使用。如何做到这一点?

kaz*_*ase 5

通过以下变通办法,可以相对容易地实现这一点:

  1. method='nearest'
  2. 再次与method='linear'; 这里的外部区域充满了np.nan
  3. 如果结果2中存在NaN,则将您的期望值分配给fill_value结果1。

码:

import numpy as np
from scipy.interpolate import griddata

def func(x, y):
    return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]

points = np.random.rand(100, 2)
values = func(points[:,0], points[:,1])

grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')

fill_value = 123  # Whatever you like
grid_z0[np.isnan(grid_z1)] = fill_value
Run Code Online (Sandbox Code Playgroud)

一种不太专门的方法是显式计算凸包并使用它来分配填充值。这将需要更多的努力,但可能会运行得更快。