Add days to date in pandas

29,222

Solution 1

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

Solution 2

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

Share:
29,222
datascana
Author by

datascana

Updated on August 03, 2020

Comments

  • datascana
    datascana almost 4 years

    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 !

  • 3kstc
    3kstc about 6 years
    How would one create NewDate by adding Days to today's date? ie df['NewDate'] = ??date_of_today?? + pd.to_timedelta(pd.np.ceil(df.Days), unit="D")
  • 3kstc
    3kstc about 6 years
    How would one add on Days to todays date and create a NewDate?
  • languitar
    languitar about 6 years
    Please open a new question. This is not directly related to the original question.
  • 3kstc
    3kstc about 6 years
    I posted a new question
  • Rahul Kumar Singh
    Rahul Kumar Singh almost 5 years
    cannot add DatetimeIndex and DatetimeIndex
  • el Josso
    el Josso almost 3 years
    Best one, for now on, use directly numpy and not from pandas pd.np.ceil(df.Days) --> np.ceil(df.Days)