我有一个如下所示的DataFrame:
raw_data = {'SeriesDate':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'Test':['1','2','3','4']}
import pandas as pd
df = pd.DataFrame(raw_data,columns=['SeriesDate','Test'])
df['SeriesDate'] = pd.to_datetime(df['SeriesDate'])
我想从日期字段中减去数字字段以到达日期,但是当我这样做时:
df['TestDate'] = df['SeriesDate'] - pd.Series((dd) for dd in df['Test'])
我得到以下TypeError:
TypeError: incompatible type [object] for a datetime/timedelta operation
我知道如何解决这个问题吗?
答案 0 :(得分:1)
您可以使用to_timedelta
:
df['TestDate'] = df['SeriesDate'] - pd.to_timedelta(df['Test'].astype(int), unit="d")
print(df)
SeriesDate Test TestDate
0 2017-03-10 1 2017-03-09
1 2017-03-13 2 2017-03-11
2 2017-03-14 3 2017-03-11
3 2017-03-15 4 2017-03-11