datascana
datascana

Reputation: 641

Add days to date in pandas

I have a data frame that contains 2 columns, one is Date and other is float number. I would like to add those 2 to get the following:

   Index           Date           Days           NewDate
     0           20-04-2016        5           25-04-2016
     1           16-03-2015       3.7          20-03-2015

As you can see if there is decimal it is converted as int as 3.1--> 4 (days). I have some weird questions so I appreciate any help. Thank you !

Upvotes: 9

Views: 37945

Answers (3)

Akhilesh_IN
Akhilesh_IN

Reputation: 1307

using combine for two columns calculations and pd.DateOffset for adding days

df['NewDate'] = df['Date'].combine(df['Days'], lambda x,y: x + pd.DateOffset(days=int(np.ceil(y))))

output:

        Date  Days    NewDate
0 2016-04-20   5.0 2016-04-25
1 2016-03-16   3.7 2016-03-20

Upvotes: 0

languitar
languitar

Reputation: 6784

First, ensure that the Date column is a datetime object:

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

Then, we can convert the Days column to int by ceiling it and the converting it to a pandas Timedelta:

temp = df['Days'].apply(np.ceil).apply(lambda x: pd.Timedelta(x, unit='D'))

Datetime objects and timedeltas can be added:

df['NewDate'] = df['Date'] + temp

Upvotes: 15

akuiper
akuiper

Reputation: 214927

You can convert the Days column to timedelta and add it to Date column:

import pandas as pd

df['NewDate'] = pd.to_datetime(df.Date) + pd.to_timedelta(pd.np.ceil(df.Days), unit="D")
df

enter image description here

Upvotes: 16

Related Questions