relativedelta - 根据列值添加月数

relativedelta - Add # of months based on column values

我想将 "exact months" 添加到开始日期以计算结束日期,并且一直在玩 relativedelta。我有以下内容:

df1['Start Date'] = ['11/1/2018', '3/15/2019', NaN, '5/15/2019', '2/28/2017', NaN, '10/31/2018']

df1['Months'] = [12.0, 36.0, 15.0, 36.0, 12.0, 9.0, 5.0]

df1['Start Date'] 当前是 datetime64[ns] 而 df1['Months'] 是 float64。

最终结果应该是 df1['Start Date'] + .df1['Months'] - 1 天,但 relativedelta 方面很重要,因为我想 return "exact months."NaN可以继续returnNaN.

这是我尝试的计算:

df1['End_Date'] = df1['Effective_Date'].apply(lambda x: x + relativedelta(months = df1['Months'].astype(float))) - pd.DateOffset(days = 1)

我收到以下错误,我不确定如何解决:

cannot convert the series to <class 'int'>

我尝试了以下方法但无济于事:

df1['Months'].astype('timedelta64[D]')

非常感谢您的帮助。

首先将列转换为日期时间,每行 axis=1 增加月份 DataFrame.apply,最后减去一天:

df1['Start Date'] = pd.to_datetime(df1['Start Date'])

f = lambda x: x['Start Date'] + relativedelta(months = int(x['Months']))
df1['End_Date'] = df1.apply(f, axis=1) - pd.DateOffset(days = 1)
print (df1)
  Start Date  Months   End_Date
0 2018-11-01    12.0 2019-10-31
1 2019-03-15    36.0 2022-03-14
2        NaT    15.0        NaT
3 2019-05-15    36.0 2022-05-14
4 2017-02-28    12.0 2018-02-27
5        NaT     9.0        NaT
6 2018-10-31     5.0 2019-03-30