【问题标题】:Pandas Fill consecutive null values with range of values between the first non null value before and after熊猫用前后第一个非空值之间的值范围填充连续的空值
【发布时间】:2021-11-03 16:48:43
【问题描述】:

我有一个数据框,我想按照两个条件在数据框中填充空值

条件一: NaN之后的值(in this example 10) > NaN之前的值(7.5)

2.75
7.5
NaN
NaN
NaN
10

从 7.5 到 10 等量递增。所以它会像

2.75
7.5
8.125
8.75
9.375
10

PS:增量计算如下(10-7.5/4) = 0.625

条件2: NaN之后的值为

2.75
10
NaN
NaN
NaN
7.5

前向填充 NaN 值

2.75
10
10
10
10
7.5

【问题讨论】:

    标签: python pandas dataframe nan ffill


    【解决方案1】:

    如果您打算为一个系列做这个,您可以使用:

    df['Col'].fillna(df['Col'].interpolate().cummax())
    

    对于数据框:

    df.fillna(df.interpolate().cummax())
    

    显示 con1 和 cond 2 的数据框(也可以为系列复制

    print(df1)
    
         Col   Col1
    0   2.75   2.75
    1   7.50  10.00
    2    NaN    NaN
    3    NaN    NaN
    4    NaN    NaN
    5  10.00   7.50
    

    print(df1.fillna(df1.interpolate().cummax()))
          Col   Col1
    0   2.750   2.75
    1   7.500  10.00
    2   8.125  10.00
    3   8.750  10.00
    4   9.375  10.00
    5  10.000   7.50
    

    【讨论】:

    • 如果您只有一个间隙,这可能会起作用。但是,问题是如果你有更多的 NaN 值,它将填充整个系列中的最大值而不是附近的值。示例:df = pd.DataFrame({'col1': [2.75, 7.5, np.NaN, np.NaN, 10, np.NaN, 3, np.NaN, 5]})。最后一个np.NaN 值将填充为 10 而不是 4
    • 所以我想我的问题是,有没有办法通过应用某个窗口来解决这个问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 2015-09-17
    • 1970-01-01
    • 2015-07-22
    • 2017-07-19
    • 1970-01-01
    相关资源
    最近更新 更多