1

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?

CDPF
  • 55
  • 6

2 Answers2

0

I had something similar. I had a column of dates of AppEntryCompleteDate and I wanted to add the the Term to it to generate a Maturity date:

This is the initial data structure (code will add Col 3 to Col 0):

enter image description here

# adds Term to AppEntryCompletedDate to create Maturity column   
keyLoanRollup['Maturity'] = keyLoanRollup.apply(lambda x: x['AppEntryCompletedDate'] + pd.DateOffset(months = x['Term']), axis=1)

This is the structure after with Maturity as a new column:

enter image description here

Bryan Butler
  • 1,750
  • 1
  • 19
  • 19
-1

A single loop was enough

import pandas as pd

dates = {'Date': ['24/04/2019','24/04/2019','2011/05/30'], 'Months':[2,12,150]}
df = pd.DataFrame(dates, columns = ['Date','Months'])
df['Add_month'] = pd.to_datetime(df['Date']).dt.date

months = [2,12,150]
j = 0
for i in df['Add_month']:
    print(i)
    print(i + pd.DateOffset(months=months[j]))
    j += 1
CDPF
  • 55
  • 6
  • Additionally this can also work: https://stackoverflow.com/questions/45670242/loop-through-dataframe-one-by-one-pandas – CDPF Jul 14 '20 at 00:28