Python将整数加到日期上,并仅返回工作日的日期,忽略周末。

2024-09-28 23:20:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的数据帧

df = pd.DataFrame({'Start_Date': ['2018-08-23', '2018-08-16', '2018-08-24', '2018-08-29'], 'Days': ['3', '1', '3', '0']})

我想创建一个新的列“结束日期”。结束日期将是开始日期+天。此外,结束日期应仅为工作日(不包括周末)。你知道吗

预计出局

Start Date      Days   End_Date
2018-08-23      3      2018-08-28    
2018-08-16      1      2018-08-17
2018-08-24      3      2018-08-29
2018-08-29      0      2018-08-29

我试过使用来自omz的解决方案,但它对我不起作用。我试过使用workday函数,但也不起作用。你知道吗

你知道吗?你知道吗


Tags: 数据函数dataframedfdate解决方案daysstart
2条回答

可以这样使用BDay

from pandas.tseries.offsets import BDay

df['Start_Date'] = pd.to_datetime(df['Start_Date'])
df['End_Date']  = df.apply(lambda x: x['Start_Date'] + BDay(x['Days']), axis=1)

输出:

   Days Start_Date   End_Date
0     3 2018-08-23 2018-08-28
1     1 2018-08-16 2018-08-17
2     3 2018-08-24 2018-08-29
3     0 2018-08-29 2018-08-29

您可以使用numpy.busday_offset获得下一个工作日。你知道吗

In [1]: import numpy as np

In [2]: df['End_Date'] = df.apply(lambda x: np.busday_offset(x[0], x[1]), axis=1)

In [3]: df
Out[3]:
   Start_Date Days   End_Date
0  2018-08-23    3 2018-08-28
1  2018-08-16    1 2018-08-17
2  2018-08-24    3 2018-08-29
3  2018-08-29    0 2018-08-29

相关问题 更多 >