Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 306
Number Logic Avatar asked Dec 05 '25 13:12

Number Logic


1 Answers

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'])
like image 78
MaxU - stop WAR against UA Avatar answered Dec 10 '25 17:12

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!