【问题标题】:Replace NaN's in an array in a specific way以特定方式替换数组中的 NaN
【发布时间】:2019-11-10 20:40:03
【问题描述】:

我有一个表单数组(此处简化):[1,NaN,NaN,7,NaN,27]。我想用已知值之间等距的值替换NaN's,因此上面的数组将变为[1,3,5,7,17,27]。有没有一种快速的方法来做到这一点(不使用一些 for 循环)?谢谢!

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    Pandas 的 dataframe.interpolate() 函数主要用于填充数据框或系列中的 NA 值

    import pandas as pd
    import numpy as np
    
    arr = [ 1, np.NaN, np.NaN, 7, np.NaN, 27]
    //converting array in series 
    print(pd.Series(arr).interpolate(method = 'linear', limit_direction = 'forward'))
    

    参数
    method = 'linear':忽略索引并将值视为等距。
    limit_direction: {'forward', 'backward', 'both'}, 默认 'forward' 如果指定了限制,则将在该方向填充连续的 NaN。
    limit:int,可选 要填充的最大连续 NaN 数。必须大于 0。

    print(pd.Series(arr).interpolate(method = 'linear', limit_direction = 'forward', limit = 1))
    #5 won't  get printed
    print(pd.Series(arr).interpolate(method = 'linear', limit_direction = 'backward', limit = 1))
    #3 won't get printed
    

    您可以根据自己的要求尝试不同的变体。

    【讨论】:

      【解决方案2】:

      如果可能,使用pandas 创建Series,然后使用Series.interpolate

      import pandas as pd
      import numpy as np
      
      arr = [1,np.NaN,np.NaN,7,np.NaN,27]
      
      print (pd.Series(arr).interpolate().values)
      [ 1.  3.  5.  7. 17. 27.]
      

      【讨论】:

        猜你喜欢
        • 2020-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 2020-02-22
        • 1970-01-01
        • 2020-10-13
        相关资源
        最近更新 更多