【问题标题】:Create a date-index using pandas date range function, but skipping the week-end days (Sat and Sun)使用 pandas 日期范围函数创建日期索引,但跳过周末(周六和周日)
【发布时间】:2019-07-04 02:29:19
【问题描述】:

我正在尝试对一些股票价格进行排序,并希望将相应的日期设置为索引。我做了类似的事情来创建索引:

date_index = pd.date_range('2018-01-01', periods = 30, freq = 'D')

问题是,我的价格表跳过了周末,并且没有考虑周六和周日。

如何创建一个也跳过 Sat 和 Sun 的索引?

【问题讨论】:

    标签: pandas date date-range


    【解决方案1】:

    使用weekday 进行过滤:

    date_index = pd.date_range('2018-01-01', periods = 30, freq = 'D')
    print (date_index[date_index.weekday < 5])
    DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
                   '2018-01-05', '2018-01-08', '2018-01-09', '2018-01-10',
                   '2018-01-11', '2018-01-12', '2018-01-15', '2018-01-16',
                   '2018-01-17', '2018-01-18', '2018-01-19', '2018-01-22',
                   '2018-01-23', '2018-01-24', '2018-01-25', '2018-01-26',
                   '2018-01-29', '2018-01-30'],
                  dtype='datetime64[ns]', freq=None)
    

    如果想用DatetimeIndex过滤行:

    print (df[df.index.weekday < 5])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多