【问题标题】:Difference between datetimes in terms of number of business days using pandas日期时间在使用熊猫的工作日数方面的差异
【发布时间】:2019-05-23 20:00:54
【问题描述】:

是否有(更)方便/有效的方法来使用 pandas 计算日期之间的工作日数?

我可以的

len(pd.bdate_range(start='2018-12-03',end='2018-12-14'))-1 # minus one only if end date is a business day

但是对于开始和结束日之间的较长距离,这似乎相当低效。

有一些建议如何使用BDay 偏移对象,但它们似乎都指的是创建日期范围或类似的东西。

我更多地考虑以工作日表示的 Timedelta 对象。

假设我有两个系列,s1 和 s2,包含日期时间。如果熊猫有类似的东西

s1.dt.subtract(s2,freq='B') 
# giving a new series containing timedeltas where the number of days calculated
# use business days only

会很好。

(numpy 有一个 busday_count() 方法。但我不想将我的 pandas 时间戳转换为 numpy,因为这会变得混乱。)

【问题讨论】:

    标签: python pandas timedelta


    【解决方案1】:

    我认为np.busday_count 这里是个好主意,也不需要转换为 numpy 数组:

    s1 = pd.Series(pd.date_range(start='05/01/2019',end='05/10/2019'))
    s2 = pd.Series(pd.date_range(start='05/04/2019',periods=10, freq='5d'))
    
    s = pd.Series([np.busday_count(a, b) for a, b in zip(s1, s2)])
    print (s)
    0     3
    1     5
    2     7
    3    10
    4    14
    5    17
    6    19
    7    23
    8    25
    9    27
    dtype: int64
    

    【讨论】:

    • 在更广泛的日期范围内对此进行了测试,以确保不会发生从 pandas 到 numpy 的奇怪时间戳转换,这可能会搞砸事情。完美运行,谢谢。
    【解决方案2】:
    from xone import calendar
    def business_dates(start, end):
        us_cal = calendar.USTradingCalendar()
        kw = dict(start=start, end=end)
        return pd.bdate_range(**kw).drop(us_cal.holidays(**kw))
    
    In [1]: business_dates(start='2018-12-20', end='2018-12-31')
    Out[1]: DatetimeIndex(['2018-12-20', '2018-12-21', '2018-12-24', '2018-12-26',
                           '2018-12-27', '2018-12-28', '2018-12-31'],
                          dtype='datetime64[ns]', freq=None)
    
    来源Get business days between start and end date using pandas

    【讨论】:

      【解决方案3】:
      #create dataframes with the dates
      df=pd.DataFrame({'dates':pd.date_range(start='05/01/2019',end='05/31/2019')})
      #check if the dates are in business days
      df[df['dates'].isin(pd.bdate_range(df['dates'].get(0), df['dates'].get(len(df)-1)))]
      
      out[]:
      0   2019-05-01
      1   2019-05-02
      2   2019-05-03
      5   2019-05-06
      6   2019-05-07
      7   2019-05-08
      8   2019-05-09
      9   2019-05-10
      12  2019-05-13
      13  2019-05-14
      14  2019-05-15
      15  2019-05-16
      16  2019-05-17
      19  2019-05-20
      20  2019-05-21
      21  2019-05-22
      22  2019-05-23
      23  2019-05-24
      26  2019-05-27
      27  2019-05-28
      28  2019-05-29
      29  2019-05-30
      30  2019-05-31
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-13
        • 2019-01-03
        • 1970-01-01
        • 1970-01-01
        • 2017-09-07
        • 2021-06-02
        • 2016-07-05
        相关资源
        最近更新 更多