What is the best drop-in replacement for numpy.interp if I want the null interpolation (piecewise constant)?

大城市里の小女人 提交于 2019-11-30 14:17:51

The scipy.interpolate.interp1d can do all kinds of interpolation: ‘linear’,’nearest’, ‘zero’, ‘slinear’, ‘quadratic, ‘cubic’.

Please check the document: http://docs.scipy.org/doc/scipy-0.10.1/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d

Just for completion: The solution to the question is the following code which I was able to write with the help of the hints given in the updated answer:

def interpolate_constant(x, xp, yp):
    indices = np.searchsorted(xp, x, side='right')
    y = np.concatenate(([0], yp))
    return y[indices]

I totally agree that kind='zero' is extremely slow; for a large data set of million rows it can take literally 1000 times slower than 'linear' method. For "left-constant" interpolation - using the latest value - the following code works:

def approx(x, y, xout, yleft=np.nan, yright=np.nan): 
    xoutIdx     = np.searchsorted(x, xout, side='right')-1
    return (np.where(xout<x[0], yleft, np.where(xout>x[-1], yright, y[xoutIdx])))

Coming from R background, this is equivalent to R's approx with f=0. I haven't found a clean way to do this for "right-constant" interpolation because python's np.searchsorted with side='right' pushes one index back if an xout value matches exactly with a value in x...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!