【问题标题】:Compare date range in python dataframe比较python数据框中的日期范围
【发布时间】:2021-12-17 14:22:52
【问题描述】:

我在 pandas.core.indexes.datetimes.DatetimeIndexDatetimeIndex 中有一个日期范围:

(['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')

此外系列数据为:

2021-03-27    2
2021-03-28    1
2021-03-30    1
2021-03-31    2
2021-04-04    3

现在,如果我想获得一个包含所有日期及其相反值的数据框,并且如果缺少任何日期,它应该将该日期作为 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
...

【问题讨论】:

    标签: python pandas dataframe series


    【解决方案1】:

    IIUC 使用Series.reindex,仅在Series 中需要DatetimeIndex 以匹配idx

    idx = 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'])
    
    
    print (s)
    2021-03-27    2
    2021-03-28    1
    2021-03-30    1
    2021-03-31    2
    2021-04-04    3
    Name: a, dtype: int64
    

    s.index = pd.to_datetime(s.index)
    s = s.reindex(idx, fill_value=0)
    print (s)
    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
    Name: a, dtype: int64
    

    如果想通过date_range 而非idx 重新索引,请使用它:

    s = s.reindex(pd.date_range('2021-03-21', '2021-04-04', freq='D'), fill_value=0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2021-12-14
      • 1970-01-01
      • 2015-06-19
      相关资源
      最近更新 更多