将天数添加到Pandas数据框中的日期

时间:2018-02-10 00:25:32

标签: python python-3.x pandas

我有以下数据框:

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]})

我想在几天内将“原始成熟度”列添加到“到期日”列。我试过像:

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

但是收到错误。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

假设df['Maturity Date']是日期时间类型:

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

如果df['Maturity Date']是字符串dtype,则需要先将其转换为日期时间:

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

答案 1 :(得分:1)

这应该有效:

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