Resample a numpy array

前端 未结 5 1269
梦如初夏
梦如初夏 2020-12-14 03:06

It\'s easy to resample an array like

 a = numpy.array([1,2,3,4,5,6,7,8,9,10])

with an integer resampling factor. For instance, wi

5条回答
  •  忘掉有多难
    2020-12-14 03:36

    NumPy has numpy.interp which does linear interpolation:

    In [1]: numpy.interp(np.arange(0, len(a), 1.5), np.arange(0, len(a)), a)
    Out[1]: array([  1. ,   2.5,   4. ,   5.5,   7. ,   8.5,  10. ])
    

    SciPy has scipy.interpolate.interp1d which can do linear and nearest interpolation (though which point is nearest might not be obvious):

    In [2]: from scipy.interpolate import interp1d
    In [3]: xp = np.arange(0, len(a), 1.5)
    In [4]: lin = interp1d(np.arange(len(a)), a)
    
    In [5]: lin(xp)
    Out[5]: array([  1. ,   2.5,   4. ,   5.5,   7. ,   8.5,  10. ])
    
    In [6]: nearest = interp1d(np.arange(len(a)), a, kind='nearest')
    
    In [7]: nearest(xp)
    Out[7]: array([  1.,   2.,   4.,   5.,   7.,   8.,  10.])
    

提交回复
热议问题