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

如何将年度周数转日期?适配Prophet建模及缺失值处理

解决方案:周数转日期 + Prophet缺失值处理

一、将年份+周数转换为对应周六的日期

可以用Python的datetime模块直接实现,利用ISO周历规则(和你的示例完全匹配:202001对应2020-01-04),代码如下:

import datetime

def convert_week_to_saturday(week_code):
    # 确保周编码是6位字符串(处理短码,比如20201转为202001)
    week_str = str(week_code).zfill(6)
    year = int(week_str[:4])
    week_num = int(week_str[4:])
    # ISO周历中1=周一,6=周六,直接生成对应日期并格式化
    return datetime.date.fromisocalendar(year, week_num, 6).strftime("%Y-%m-%d")

# 测试示例
sample_weeks = [202001, 202002, 202003]
result_dates = [convert_week_to_saturday(w) for w in sample_weeks]
# 输出: ['2020-01-04', '2020-01-11', '2020-01-18']

如果用Pandas处理批量数据,效率更高:

import pandas as pd

df = pd.DataFrame({"week": [202001, 202002, 202003, 202005]})
# 拆分年份和周数
df["year"] = df["week"].astype(str).str[:4].astype(int)
df["week_num"] = df["week"].astype(str).str[4:].astype(int)
# 生成周六日期
df["ds"] = df.apply(lambda row: datetime.date.fromisocalendar(row["year"], row["week_num"], 6), axis=1)
# 格式化字符串(可选,Prophet接受datetime类型的ds列)
df["ds"] = df["ds"].dt.strftime("%Y-%m-%d")

二、Prophet模型的缺失值处理建议

不需要直接补0,分两种场景处理:

  • 场景1:缺失的周本来就没有数据(比如非业务周、无记录产生):直接保留现有样本即可。Prophet不需要连续的时间序列,它会基于已有观测的时间间隔自动拟合趋势和季节性,缺失的时间段不会干扰模型训练。
  • 场景2:缺失的周是数据丢失(本该有值但未记录):优先用业务逻辑或插值法填充,比如:
    • 用前后周的均值/中位数填充
    • 用Pandas的时间序列插值(df.interpolate(method='time'))
    • 只有当业务明确这些周的数值为0时,才补0

另外,Prophet在预测阶段会自动生成连续的日期序列(不管训练数据是否连续),所以训练时无需强制补全所有周数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:10:30