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

Python Pandas中基于全量日期范围补全Series缺失值为0的实现方法

解决方法

直接使用pandas的reindex方法即可实现需求,只需要指定完整日期索引、缺失值填充为0就行。

核心代码

# 其中full_date_index为你已有的完整DatetimeIndex,original_series为原始时间序列
result = original_series.reindex(full_date_index, fill_value=0)

完整可复现示例

import pandas as pd

# 构造完整日期索引
full_date_index = pd.DatetimeIndex(
    ['2021-03-21', '2021-03-22', '2021-03-23', '2021-03-24',
     '2021-03-25', '2021-03-26', '2021-03-27', '2021-03-28',
     '2021-03-29', '2021-03-30', '2021-03-31', '2021-04-01',
     '2021-04-02', '2021-04-03', '2021-04-04'],
    dtype='datetime64[ns]', freq='D'
)

# 构造原始时间序列
original_series = pd.Series(
    data=[2, 1, 1, 2, 3],
    index=pd.to_datetime(['2021-03-27', '2021-03-28', '2021-03-30', '2021-03-31', '2021-04-04'])
)

# 生成结果
result = original_series.reindex(full_date_index, fill_value=0)

# 打印结果
print(result)

输出结果

2021-03-21    0
2021-03-22    0
2021-03-23    0
2021-03-24    0
2021-03-25    0
2021-03-26    0
2021-03-27    2
2021-03-28    1
2021-03-29    0
2021-03-30    1
2021-03-31    2
2021-04-01    0
2021-04-02    0
2021-04-03    0
2021-04-04    3
Freq: D, dtype: int64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 18:06:06