Number Logic
Number Logic

Reputation: 894

Adding Days to a date in a Pandas dataframe

I have the following dataframe:

import pandas as pd
df= pd.DataFrame({'type':['Asset','Liability'],'Amount':\
[10,-5],'Maturity Date':['2018-01-22','2018-01-23'],\
'Original Maturity':[1,2]})

I want to add the 'Original Maturity' column in days to the 'Maturity Date' column. I tried something like:

df['Maturity Date']=df['Maturity Date']+pd.to_datetime(df['Original Maturity']).dt.days

but get an error. Any suggestions ?

Upvotes: 3

Views: 3901

Answers (2)

jpp
jpp

Reputation: 164613

This should work:

df['Maturity Date'] = pd.to_datetime(df['Maturity Date'])
df['Maturity Date'] += df['Original Maturity'].map(pd.offsets.Day)

Upvotes: 1

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210822

Assuming df['Maturity Date'] is of datetime type:

In [24]: df['Maturity Date'] += pd.to_timedelta(df['Original Maturity'], unit='D')

In [25]: df
Out[25]:
   Amount Maturity Date  Original Maturity       type
0      10    2018-01-23                  1      Asset
1      -5    2018-01-25                  2  Liability

If df['Maturity Date'] is a string dtype you would need to convert it to datetime first:

df['Maturity Date'] = pd.to_datetime(df['Maturity Date'])

Upvotes: 5

Related Questions