I want to add a column with a number of months to a column with dates. So far I have tried (pd.DateOffset(months=plus_month_period)) however ‘months’ wont accept a column, just a number. My most successful attempt has been the following:
dates = {'Date': ['24/04/2019','24/04/2019','2011/05/30'], 'Months':[2,12,100]}
df = pd.DataFrame(dates, columns = ['Date','Months'])
month_sum = pd.to_datetime(df['Date']).dt.to_period('m')
df['Add_month'] = ((month_sum + np.array(df['Months'])).dt.strftime('%Y/%m')).astype(str) + '/' + (pd.to_datetime(df['Date']).dt.day).astype(str)
print(pd.to_datetime(df['Add_month']))
This results in:
0 2019-06-24
1 2020-04-24
2 2023-11-30
My problem with this solution is that when creating the column df['Add_month'] I’m basically adding a hard-coded string at the end in an attempt to add the ‘day’ part, sometimes resulting in inaccurate calculations. Is there a more direct method to add the Months column and the Date columns?