【问题标题】:Problems reindexing a dataframe重新索引数据框的问题
【发布时间】:2021-11-27 19:38:21
【问题描述】:

我有一个标记为 df_2 的 df 缺少一些日期,我想重新索引数据框以包含索引范围内的所有日期,并在没有可用数据的情况下使用 0。当我使用以下代码时,我最终得到一个全为 0 的数据框,而不是在索引中日期已经可用的填充行和日期不可用的 0 行。请注意,我还尝试使用 date_range() 重新索引 df,并产生了相同的错误 df,全为 0:

df_2.head()

DATE        TOTAL_SALES  TOTAL_TRAFFIC
2018-01-02        36904         4974.0
2018-01-03        33303         4610.0
2018-01-04        29485         4493.0
2018-01-05        33017         4246.0
2018-01-06        44762         5081.0

idx = pd.period_range(min(df_2.index), max(df_2.index))
df_3 = df_2.reindex(idx, fill_value=0)

df_3.head()

            TOTAL_SALES  TOTAL_TRAFFIC
2018-01-02            0            0.0
2018-01-03            0            0.0
2018-01-04            0            0.0
2018-01-05            0            0.0
2018-01-06            0            0.0

【问题讨论】:

    标签: python pandas dataframe reindex


    【解决方案1】:

    DatetimeIndex 不是PeriodIndex。你应该使用date_range 而不是period_range

    idx = pd.date_range(df_2.index.min(), df_2.index.max())
    df_3 = df_2.reindex(idx, fill_value=0)
    print(df3.head())
    
    # Output:
                TOTAL_SALES  TOTAL_TRAFFIC
    2018-01-02        36904         4974.0
    2018-01-03        33303         4610.0
    2018-01-04        29485         4493.0
    2018-01-05        33017         4246.0
    2018-01-06        44762         5081.0
    

    【讨论】:

    • 感谢您的回复,Corralien!尽管数据框仅包含零,但我仍然遇到同样的问题...
    • 你能分享你的数据文件吗?
    猜你喜欢
    • 2020-03-30
    • 2020-04-16
    • 2014-10-04
    • 2016-06-13
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多