【问题标题】:Extraploation with 'nearest' method in Python在 Python 中使用“最近”方法进行外推
【发布时间】:2014-01-26 23:24:43
【问题描述】:

我正在寻找与以下 Matlab 语句等效的 Python 语句:

vq interp1(x,y, xq,'nearest','extrap')

看起来interp(xq, x, y) 非常适合线性插值/外插。

我也看了

F = scipy.interpolate.interp1d(x, y, kind='nearest')

这对于最近的方法非常有效,但不会执行外推。

还有什么我忽略的吗?谢谢。

【问题讨论】:

    标签: python scipy extrapolation


    【解决方案1】:

    对于将使用最近插值进行外推的线性插值,请使用numpy.interp。默认情况下会这样做。

    例如:

    yi = np.interp(xi, x, y)
    

    否则,如果您只想在任何地方进行最近的插值,正如您所描述的,您可以以简短但低效的方式进行:(如果您愿意,可以将其设为单线)

    def nearest_interp(xi, x, y):
        idx = np.abs(x - xi[:,None])
        return y[idx.argmin(axis=1)]
    

    或者以更有效的方式使用searchsorted

    def fast_nearest_interp(xi, x, y):
        """Assumes that x is monotonically increasing!!."""
        # Shift x points to centers
        spacing = np.diff(x) / 2
        x = x + np.hstack([spacing, spacing[-1]])
        # Append the last point in y twice for ease of use
        y = np.hstack([y, y[-1]])
        return y[np.searchsorted(x, xi)]
    

    为了说明numpy.interp 和上面最接近的插值示例之间的区别:

    import numpy as np
    import matplotlib.pyplot as plt
    
    def main():
        x = np.array([0.1, 0.3, 1.9])
        y = np.array([4, -9, 1])
        xi = np.linspace(-1, 3, 200)
    
        fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
        for ax in axes:
            ax.margins(0.05)
            ax.plot(x, y, 'ro')
    
        axes[0].plot(xi, np.interp(xi, x, y), color='blue')
        axes[1].plot(xi, nearest_interp(xi, x, y), color='green')
    
        kwargs = dict(x=0.95, y=0.9, ha='right', va='top')
        axes[0].set_title("Numpy's $interp$ function", **kwargs)
        axes[1].set_title('Nearest Interpolation', **kwargs)
    
        plt.show()
    
    def nearest_interp(xi, x, y):
        idx = np.abs(x - xi[:,None])
        return y[idx.argmin(axis=1)]
    
    main()
    

    【讨论】:

      【解决方案2】:

      在更高版本的 SciPy(至少 v0.19.1+)中,scipy.interpolate.interp1d 具有选项fill_value = “extrapolate”

      例如:

      import pandas as pd
      >>> s = pd.Series([1, 2, 3])
      Out[1]: 
      0    1
      1    2
      2    3
      dtype: int64
      
      >>> t = pd.concat([s, pd.Series(index=s.index + 0.1)]).sort_index()
      Out[2]: 
      0.0    1.0
      0.1    NaN
      1.0    2.0
      1.1    NaN
      2.0    3.0
      2.1    NaN
      dtype: float64
      
      >>> t.interpolate(method='nearest')
      Out[3]: 
      0.0    1.0
      0.1    1.0
      1.0    2.0
      1.1    2.0
      2.0    3.0
      2.1    NaN
      dtype: float64
      
      >>> t.interpolate(method='nearest', fill_value='extrapolate')
      Out[4]: 
      0.0    1.0
      0.1    1.0
      1.0    2.0
      1.1    2.0
      2.0    3.0
      2.1    3.0
      dtype: float64
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-18
        • 2016-09-26
        • 2013-12-29
        • 2016-03-06
        • 2011-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多