how to use Python relativedelta(or other ways) calculate 'Date after Months' in this dataframe?

Question:

<How to calcurate Date after months?>
Date after months

|Date       |months |Date after months|
|12/31/2021 |128    |
|1/11/2022  |5      |
|10/2/2020  |67     |
Asked By: Domingo

||

Answers:

Edit: it looks like there is a bug in DateOffset (12/31/2021 + 128 months is giving 08/28/2032 incorrectly) when applied on a Series, see the alternative for a workaround.

Assuming , you can use a DateOffset:

df['Date after months'] = (pd
 .to_datetime(df['Date'])
 .add(pd.DateOffset(months=1)*df['months'])
 .dt.strftime('%m/%d/%Y')
)

Output:

         Date  months Date after months
0  12/31/2021     128        08/28/2032
1   1/11/2022       5        06/11/2022
2   10/2/2020      67        05/02/2026

alternative

df['Date after months'] = (pd
  .Series([d+pd.DateOffset(months=x)
           for d, x in zip(pd.to_datetime(df['Date']), df['months'])],
          index=df.index)
  .dt.strftime('%m/%d/%Y')
 )
         Date  months Date after months
0  12/31/2021     128        08/31/2032
1   1/11/2022       5        06/11/2022
2   10/2/2020      67        05/02/2026
Answered By: mozway