Skip to main content
 首页 » 编程设计

python Pandas : Making date index continuous

2025年05月04日15oomusou

我有以下时间序列数据:

           EventCount 
Date 
2015-06-23          1     
2015-06-25          1 
2015-05-29          1 

我需要填充数据,所以索引有连续的日期,像这样:

           EventCount 
Date 
2015-06-23          1 
2015-06-24          0 
2015-06-25          1 
2015-06-26          0 
2015-06-27          0 
2015-06-28          0 
2015-05-29          1 

我该怎么做?

请您参考如下方法:

您可以使用 .reindex()。

# your data 
# =================================== 
print(df) 
 
            EventCount 
Date                   
2015-06-23           1 
2015-06-25           1 
2015-06-29           1 
 
# processing 
# ============================== 
df.reindex(pd.date_range(df.index[0], df.index[-1], freq='D')).fillna(0) 
 
            EventCount 
2015-06-23           1 
2015-06-24           0 
2015-06-25           1 
2015-06-26           0 
2015-06-27           0 
2015-06-28           0 
2015-06-29           1