首页 文章

使用numpy.interp进行线性插值

提问于
浏览
10

我有一个浮点数的一维数组A,其中大部分是好的,但缺少一些值 . 丢失的数据被替换为nan(不是数字) . 我必须通过线性插值从附近的好值中替换数组中的缺失值 . 所以,例如:

F7(np.array([10.,20.,nan,40.,50.,nan,30.]))

应该回来

np.array([10.,20.,30.,40.,50.,40.,30.]).

使用Python做到这一点最好的方法是什么?

任何帮助将非常感激

谢谢

3 回答

  • 13

    你可以使用scipy.interpolate.interp1d

    >>> from scipy.interpolate import interp1d
    >>> import numpy as np
    >>> x = np.array([10., 20., np.nan, 40., 50., np.nan, 30.])
    >>> not_nan = np.logical_not(np.isnan(x))
    >>> indices = np.arange(len(x))
    >>> interp = interp1d(indices[not_nan], x[not_nan])
    >>> interp(indices)
    array([ 10.,  20.,  30.,  40.,  50.,  40.,  30.])
    

    EDIT :我花了一段时间才弄明白 np.interp 的工作原理,但这也可以完成这项工作:

    >>> np.interp(indices, indices[not_nan], x[not_nan])
    array([ 10.,  20.,  30.,  40.,  50.,  40.,  30.])
    
  • 7

    我会选择 pandas . 使用oneliner的简约方法:

    from pandas import *
    a=np.array([10.,20.,nan,40.,50.,nan,30.])
    Series(a).interpolate()   
    
    Out[219]:
    0    10
    1    20
    2    30
    3    40
    4    50
    5    40
    6    30
    

    或者,如果您想将其保留为数组:

    Series(a).interpolate().values
    
    Out[221]:
    array([ 10.,  20.,  30.,  40.,  50.,  40.,  30.])
    
  • 0

    要在每次要插入数据时不在系列中创建新的Series对象或新项,请使用RedBlackPy . 请参阅以下代码示例:

    import redblackpy as rb
    
    # we do not include missing data
    index = [0,1,3,4,6]
    data = [10,20,40,50,30]
    # create Series object
    series = rb.Series(index=index, values=data, dtype='float32',
                       interpolate='linear')
    
    # Now you have access at any key using linear interpolation
    # Interpolation does not creates new items in Series
    print(series[2]) # prints 30
    print(series[5]) # prints 40
    # print Series and see that keys 2 and 5 do not exist in series
    print(series)
    

    最后一个输出如下:

    Series object Untitled
    0: 10.0
    1: 20.0
    3: 40.0
    4: 50.0
    6: 30.0
    

相关问题