You need to enable JavaScript to run this app. Python DataFrame如何循环复用历史值填充Time列末尾的NaN值
优惠活动
大模型
产品
解决方案
定价
更多

Python DataFrame如何循环复用历史值填充Time列末尾的NaN值

解决方案

核心思路是先提取Time列所有已有的非空历史值,按原出现顺序循环重复生成和DataFrame长度一致的序列,直接替换原Time列即可。

基础实现(易读)

import pandas as pd

# 提取Time列所有非空值,顺序和原列出现顺序一致
hist_time_list = df["Time"].dropna().tolist()
hist_length = len(hist_time_list)
total_length = len(df)

# 按索引取余循环复用历史值,生成完整序列
df["Time"] = [hist_time_list[i % hist_length] for i in range(total_length)]

高性能实现(适合万行以上大数据量)

借助numpy的tile方法做向量化运算,效率更高:

import pandas as pd
import numpy as np

hist_time_arr = df["Time"].dropna().values
hist_length = len(hist_time_arr)
total_length = len(df)

# 重复历史值序列足够多次后,截取前total_length个元素
df["Time"] = np.tile(hist_time_arr, int(np.ceil(total_length / hist_length)))[:total_length]

效果验证

你给出的示例中,Time列非空历史值共3个,按顺序为["2021-03-01 11:00", "2021-05-01 8:00", "2021-05-01 5:00"],填充时第4行(索引为3)取3%3=0对应第一个历史值,第5行取4%3=1对应第二个历史值,完全匹配你给出的期望输出。

如果你需要先对历史时间值排序再复用,可以在提取历史值时添加排序步骤:df["Time"].dropna().sort_values().tolist()


内容的提问来源于stack exchange,提问作者Eli Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:54:02