You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas如何按指定规则填充前后非空值之间的连续NaN空值

Pandas 条件填充空值实现方案

核心逻辑是先提前生成三种处理结果,再按照条件筛选最终填充值,步骤如下:

  1. 分别计算目标列的前向填充结果、后向填充结果、线性插值结果
  2. 对空值位置判断:如果后值>前值,使用插值结果,否则使用前向填充结果
  3. 保留原有的非空值不变

完整实现代码

import pandas as pd
import numpy as np

def custom_fill(series):
    # 提前计算三种预处理结果
    ffill_val = series.ffill()
    bfill_val = series.bfill()
    linear_interp = series.interpolate(method='linear')
    # 按条件筛选最终值
    res = np.where(
        series.isna(),  # 仅处理空值位置
        np.where(bfill_val > ffill_val, linear_interp, ffill_val),
        series  # 非空值直接保留原值
    )
    return pd.Series(res, index=series.index)

# 测试示例
if __name__ == "__main__":
    # 条件1测试数据
    s1 = pd.Series([2.75, 7.5, np.nan, np.nan, np.nan, 10])
    print("条件1填充结果:")
    print(custom_fill(s1))
    # 条件2测试数据
    s2 = pd.Series([2.75, 10, np.nan, np.nan, np.nan, 7.5])
    print("\n条件2填充结果:")
    print(custom_fill(s2))

输出结果

条件1输出

0     2.750
1     7.500
2     8.125
3     8.750
4     9.375
5    10.000
dtype: float64

条件2输出

0     2.75
1    10.00
2    10.00
3    10.00
4    10.00
5     7.50
dtype: float64

如果是对DataFrame的指定列处理,直接调用df['目标列名'] = custom_fill(df['目标列名'])即可。

内容的提问来源于stack exchange,提问作者A.Shoman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:54:01