【问题标题】:Create regular time series from irregular interval with python使用python从不规则间隔创建规则时间序列
【发布时间】:2021-01-08 05:23:36
【问题描述】:

我想知道是否可以将不规则的时间序列间隔转换为规则的时间序列间隔,而无需像这样从其他列插入值:

Index                  count
2018-01-05 00:00:00      1
2018-01-07 00:00:00      4
2018-01-08 00:00:00      15
2018-01-11 00:00:00      2
2018-01-14 00:00:00      5
2018-01-19 00:00:00      5
....

2018-12-26 00:00:00      6
2018-12-29 00:00:00      7
2018-12-30 00:00:00      8

我希望结果是这样的:

Index                  count
2018-01-01 00:00:00      0
2018-01-02 00:00:00      0
2018-01-03 00:00:00      0
2018-01-04 00:00:00      0
2018-01-05 00:00:00      1
2018-01-06 00:00:00      0
2018-01-07 00:00:00      4
2018-01-08 00:00:00      15
2018-01-09 00:00:00      0
2018-01-10 00:00:00      0
2018-01-11 00:00:00      2
2018-01-12 00:00:00      0
2018-01-13 00:00:00      0
2018-01-14 00:00:00      5
2018-01-15 00:00:00      0
2018-01-16 00:00:00      0
2018-01-17 00:00:00      0
2018-01-18 00:00:00      0
2018-01-19 00:00:00      5
....

2018-12-26 00:00:00      6
2018-12-27 00:00:00      0
2018-12-28 00:00:00      0
2018-12-29 00:00:00      7
2018-12-30 00:00:00      8
2018-12-31 00:00:00      0

所以,到目前为止,我只是尝试从 pandas 重新采样,但这只是部分解决了我的问题。

提前致谢

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    DataFrame.reindexdate_range 一起使用:

    #if necessary
    df.index = pd.to_datetime(df.index)
    
    df = df.reindex(pd.date_range('2018-01-01','2018-12-31'), fill_value=0)
    print (df)
                count
    2018-01-01      0
    2018-01-02      0
    2018-01-03      0
    2018-01-04      0
    2018-01-05      1
              ...
    2018-12-27      0
    2018-12-28      0
    2018-12-29      7
    2018-12-30      8
    2018-12-31      0
    
    [365 rows x 1 columns]
    

    【讨论】:

    • 谢谢!它完美地工作!从来不知道有一个重新索引来填补日期范围内的空白:)
    猜你喜欢
    • 2012-05-12
    • 2011-06-16
    • 2016-03-14
    • 1970-01-01
    • 2016-04-07
    • 2011-04-23
    • 2014-09-02
    • 2023-01-20
    • 2014-11-08
    相关资源
    最近更新 更多