Home > other >  How to add a column with number of years to another column with dates with Pandas
How to add a column with number of years to another column with dates with Pandas

Time:09-17

Let me show an example to better explain my problem:

I have a dataframe with a Date column and Number of Years column. I am trying to create the New Date column by adding the number of years to the years of the Date column, as the example below:

Date Number_Years New Date
2020-09-23 5 2025-09-23
2019-11-09 7 2026-11-09
2014-08-08 3 2017-08-08

I have tried the following:

df1['New Date'] = pd.to_datetime(df1['Date'])   pd.to_timedelta(df1['Number_Years'] , unit='Y')

I get an error and the following is not quite what I need, because I just need the four digit year to change on the date:

df1['New Date'] = pd.to_datetime(df1['Date'])   pd.to_timedelta(df1['Number_Years']*365 , unit='D')

Also tried:

df1['New Date'] = df1['Date']   pd.offsets.DateOffset(years=df1['Number_Years'])

and it does not work either.

Any suggestions? Thanks

CodePudding user response:

Use astype:

df['New Date'] = df['Date'].astype('datetime64[D]') \
                   df['Number_Years'].astype('timedelta64[Y]')

Output:

>>> df
         Date  Number_Years   New Date
0  2020-09-23             5 2025-09-23
1  2019-11-09             7 2026-11-09
2  2014-08-08             3 2017-08-08
  • Related