Reputation: 5300
I would like to transform a column in my data set that has number of days from the start date of a period into a date.
Here's an example of what I am trying to achieve in pandas:
#This doesn't not work
sdate = datetime(2015, 10, 1)
ndf['Date'] = ndf['Date'].apply(lambda x: sdate + x)
Upvotes: 1
Views: 70
Reputation: 90859
You would need to convert your 'Date'
column to timedelta
and then add the sdate
to it.
An Example of vectorized way of doing it -
sdate = datetime(2015, 10, 1)
ndf['Date'] = pd.to_timedelta(ndf['Date'],unit='d') + sdate
This would make the column to be of type datetime
(not string).
Demo -
In [18]: from datetime import datetime
In [19]: sdate = datetime(2015, 10, 1)
In [20]: df
Out[20]:
Date
0 1
1 1
2 3
3 5
In [21]: df['Date'] = pd.to_timedelta(df['Date'],unit='d') + sdate
In [22]: df
Out[22]:
Date
0 2015-10-02
1 2015-10-02
2 2015-10-04
3 2015-10-06
Upvotes: 2