Skip to content
Advertisement

Using pandas dateoffset and step forward num_years (given by a column)

I have a dataframe with column of datetime “Date_Begin”. I have another column “Years_to_add”. I want to calculate a third column with the “DateBegin” stepped forward by the number of years in the “years_to_add” column. I want to avoid using approximations like 365.25 in a year. I want simply add the number of years in a calendar sense (I know there will be problems with adding a year to 29 Feb).

In my version of pandas I can’t use years as timedelta (no longer supported), so I am using the DateOffset method.

I can’t get the syntax right. I have tried the following, based on suggestions from here:

df["begin_date"] + pd.DateOffset(years=int(df["years_to_add"]))

df["begin_date"] + df["years_to_add"].apply(pd.DateOffset.years)

Advertisement

Answer

Just pass it as lambda function

df["begin_date"] + df["years_to_add"].apply(lambda y: pd.DateOffset(years=y))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement