TylerNG
TylerNG

Reputation: 941

pandas add a value column to datetime

I have this simple problem but for some reason it's giving a headache. I want to add a existing Date column with another column to get a newDate column.

For example: I have Date and n columns, and I want to add in NewDate column into my existing df.

df:

Date         n     NewDate (New Calculation here: Date + n)    
05/31/2017   3     08/31/2017  
01/31/2017   4     05/31/2017
12/31/2016   2     02/28/2017

I tried:

df['NewDate'] = (pd.to_datetime(df['Date']) + MonthEnd(n)) 

but I get an error saying "cannot convert the series to class 'int'

Upvotes: 1

Views: 2687

Answers (1)

cs95
cs95

Reputation: 402263

You're probably looking for an addition with a timedelta object.

v = pd.to_datetime(df.Date) + (pd.to_timedelta(df.n, unit='M'))
v

0   2017-08-30 07:27:18
1   2017-06-01 17:56:24
2   2017-03-01 20:58:12
dtype: datetime64[ns]

At the end, you can convert the result back into the same format as before -

df['NewDate'] = v.dt.strftime('%m/%d/%Y') 

Upvotes: 2

Related Questions