Pandas处理日期索引缺失

作者: 测试探索 | 来源:发表于2021-08-29 10:10 被阅读0次

    问题:按日期统计的数据,缺失了某天,导致数据不全该怎么补充日期?

    1、数据准备
    import pandas as pd
    import matplotlib.pyplot as plt  #画图需要的包
    
    df = pd.DataFrame({
        "pdate": ["2019-12-01", "2019-12-02", "2019-12-04", "2019-12-05"],
        "pv": [100, 200, 400, 500],
        "uv": [10, 20, 40, 50],
    })
    print(df)
    
    df.set_index("pdate").plot()
    plt.show()
    
    image.png
    image.png

    可以用两种方法实现:

    一、DataFrame.reindex,调整dataframe的索引以适应新的索引
    1、将df的索引变成日期索引
    df_date = df.set_index("pdate")
    print(df_date.index)
    df_date = df_date.set_index(pd.to_datetime(df_date.index))
    print(df_date.index)
    
    image.png
    2、使用pandas.reindex填充缺失的索引
    #设置连续日期索引
    pdates = pd.date_range(start="2019-12-01", end="2019-12-05")
    print(pdates)
    
    df_date_new = df_date.reindex(pdates, fill_value=0)
    print(df_date_new)
    df_date_new.plot()
    plt.show()
    
    image.png
    image.png

    二、DataFrame.resample,可以对时间序列重采样,支持补充缺失值

    1、将索引变成日期索引
    df_new2 = df.set_index(pd.to_datetime(df["pdate"])).drop("pdate", axis=1)
    print(df_new2)
    
    image.png
    2、使用dataframe的resample的方法按照天重采样

    resample的含义:
    改变数据的时间频率,比如把天数据变成月份,或者把小时数据变成分钟级别

    resample的语法:
    (DataFrame or Series).resample(arguments).(aggregate function)
    https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases

    #reresample的参数代表天,具体使用可参照上面的链接
    df_new2 = df_new2.resample("D").mean().fillna(0)
    print(df_new2)
    
    image.png
    df_new3 = df_new2.resample("2D").mean()
    print(df_new3)
    
    image.png

    相关文章

      网友评论

        本文标题:Pandas处理日期索引缺失

        本文链接:https://www.haomeiwen.com/subject/puswiltx.html