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

如何基于首尾值逐次取均值填充缺失值?求Python或pandas优化方案

实现方案

纯Python实现

采用队列做广度优先搜索(BFS)处理区间,避免递归深度限制,时间复杂度为O(n),n为序列总长度:

import math
from collections import deque

def fill_missing(arr):
    # 拷贝原数组避免修改输入
    res = arr.copy()
    n = len(res)
    # 队列存储待处理的[起始索引, 结束索引]区间,默认首尾为有效值
    q = deque()
    q.append((0, n-1))
    
    while q:
        start, end = q.popleft()
        # 区间相邻无空缺直接跳过
        if end - start <= 1:
            continue
        # 计算区间中间位置
        mid = (start + end) // 2
        if math.isnan(res[mid]):
            res[mid] = (res[start] + res[end]) / 2
        # 拆分左右子区间加入队列继续处理
        q.append((start, mid))
        q.append((mid, end))
    return res

测试示例

# 输入你提供的测试序列
l = [10, math.nan, math.nan, math.nan, math.nan, 20]
filled_l = fill_missing(l)
print(filled_l)
# 输出:[10, 12.5, 15, 17.5, 18.75, 20]

Pandas实现

如果需要处理pandas Series类型的序列,适配代码如下:

import pandas as pd
from collections import deque

def fill_series_missing(s):
    res = s.copy().to_list()
    n = len(res)
    q = deque()
    q.append((0, n-1))
    while q:
        start, end = q.popleft()
        if end - start <= 1:
            continue
        mid = (start + end) // 2
        if pd.isna(res[mid]):
            res[mid] = (res[start] + res[end]) / 2
        q.append((start, mid))
        q.append((mid, end))
    return pd.Series(res, index=s.index)

测试示例

s = pd.Series([10, pd.NA, pd.NA, pd.NA, pd.NA, 20])
filled_s = fill_series_missing(s)
print(filled_s)

内容的提问来源于stack exchange,提问作者Mohamed Thasin ah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:45:08