Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas add day to date and the number of day based on another column

Tags:

python

pandas

In python, my dataframe like:

date1 num
2017-03-02 8
2017-04-15 4
2017-06-30 1

I want the result dataframe(add date2 columns) like this:

date1 num date2
2017-03-02 8 2017-03-10
2017-04-15 4 2017-04-19
2017-06-30 1 2017-07-01

I know :df.date1 +pd.offsets.Day(x), but x is not allowed to be Series. And I know apply() function may could resolve this problem, but the lines of my dataframe is over one billion.

So what to do?

like image 247
JoeKevin Avatar asked Sep 11 '25 04:09

JoeKevin


1 Answers

you can add timedeltas created by to_timedelta:

df['date2'] = df['date1'] + pd.to_timedelta(df['num'], unit='d')
print (df)
       date1  num      date2
0 2017-03-02    8 2017-03-10
1 2017-04-15    4 2017-04-19
2 2017-06-30    1 2017-07-01

If want add months use apply with axis=1 for proceses by rows and dateoffset:

df['date3'] = df.apply(lambda x: x['date1'] + pd.offsets.DateOffset(months=x['num']), 1)
print (df)
       date1  num      date3
0 2017-03-02    8 2017-11-02
1 2017-04-15    4 2017-08-15
2 2017-06-30    1 2017-07-30
like image 108
jezrael Avatar answered Sep 13 '25 19:09

jezrael