Search code examples
pythonpandasdataframepython-datetime

Python pandas add a years integer column to a date column


I have a question somehow similar to what discussed here How to add a year to a column of dates in pandas however in my case, the number of years to add to the date column is stored in another column. This is my not working code:

import datetime
import pandas as pd
df1 = pd.DataFrame( [ ["Tom",5], ['Jane',3],['Peter',1]],  columns = ["Name","Years"])
df1['Date'] = datetime.date.today()
df1['Final_Date'] = df1['Date'] + pd.offsets.DateOffset(years=df1['Years'])

The goal is to add 5 years to the current date for row 1, 3 years to current date in row 2, eccetera. Any suggestions? Thank you


Solution

  • Convert to time delta by converting years to days, then adding to a converted datetime column:

    df1['Final_Date'] = pd.to_datetime(df1['Date']) \
        + pd.to_timedelta(df1['Years'] * 365, unit='D')
    

    Use of to_timedelta with unit='Y' for years is deprecated and throws ValueError.

    Edit. If you need day-exact changes, you will need to go row-by-row and update the date objects accordingly. Other answers explain.