Reputation: 43
I'm trying to increase dates in the pandas dataframe by values contained in the other column of the same dataframe like this
loans['est_close_date'] = loans['dealdate'] + loans['tenor_weeks'].apply(lambda x: dt.timedelta(weeks =x))
but I keep getting error as:
"unsupported type for timedelta weeks component: numpy.int64" error.
On the other hand, construction like this
loans['est_close_date'] = loans['dealdate'] + loans['tenor_weeks'].apply(lambda x: dt.timedelta(weeks =1)*x)
works just fine. I can't understand what's wrong with the first approach.
There is no missing values in tenor_weeks
column.
Thank you in advance!
Upvotes: 4
Views: 5239
Reputation: 862511
For me you solutions work perfectly, maybe necessary upgrade pandas/python.
I add pure pandas solution with to_timedelta
:
rng = pd.date_range('2017-04-03', periods=10)
loans = pd.DataFrame({'dealdate': rng, 'tenor_weeks': range(1,11)})
print (loans)
dealdate tenor_weeks
0 2017-04-03 1
1 2017-04-04 2
2 2017-04-05 3
3 2017-04-06 4
4 2017-04-07 5
5 2017-04-08 6
6 2017-04-09 7
7 2017-04-10 8
8 2017-04-11 9
9 2017-04-12 10
loans['est_close_date'] = loans['dealdate'] + loans['tenor_weeks'].apply(lambda x: dt.timedelta(weeks =x))
loans['est_close_date1'] = loans['dealdate'] + loans['tenor_weeks'].apply(lambda x: dt.timedelta(weeks =1)*x)
loans['est_close_date2'] = loans['dealdate'] + pd.to_timedelta(loans['tenor_weeks'],unit='w')
print (loans)
dealdate tenor_weeks est_close_date est_close_date1 est_close_date2
0 2017-04-03 1 2017-04-10 2017-04-10 2017-04-10
1 2017-04-04 2 2017-04-18 2017-04-18 2017-04-18
2 2017-04-05 3 2017-04-26 2017-04-26 2017-04-26
3 2017-04-06 4 2017-05-04 2017-05-04 2017-05-04
4 2017-04-07 5 2017-05-12 2017-05-12 2017-05-12
5 2017-04-08 6 2017-05-20 2017-05-20 2017-05-20
6 2017-04-09 7 2017-05-28 2017-05-28 2017-05-28
7 2017-04-10 8 2017-06-05 2017-06-05 2017-06-05
8 2017-04-11 9 2017-06-13 2017-06-13 2017-06-13
9 2017-04-12 10 2017-06-21 2017-06-21 2017-06-21
Upvotes: 4