Sabrine Bendimerad
Sabrine Bendimerad

Reputation: 61

change year of datetime column by the year of another column + 1

I want to calculate the anniversary column by this way : keep the date and month, and change the year to the same year as start column + 1

This is my pandas dataframe :

| index |   start       |      end       |     anniversary|   
| ----- | -----------   | -------------- | -------------- | 
| 0     |   2008-02-11  |    2009-03-13  |   2009-02-11   |     
| 1     |   2009-03-13  |    2010-03-13  |   2009-02-11   |     
| 2     |   2010-03-13  |    2011-03-15  |   2009-02-11   |     

What i want to get :

| index |   start       |      end       |     anniversary|   
| ----- | -----------   | -------------- | -------------- | 
| 0     |   2008-02-11  |    2009-03-13  |   2009-02-11   |     
| 1     |   2009-03-13  |    2010-03-13  |   2010-02-11   |     
| 2     |   2010-03-13  |    2011-09-19  |   2011-02-11   |      

Upvotes: 3

Views: 1899

Answers (2)

Corralien
Corralien

Reputation: 120391

Just for fun an one-liner implementation:

out = df.assign(anniversary=pd.to_datetime(pd.concat(
          [df["start"].dt.year + 1, df["anniversary"].dt.month, df["anniversary"].dt.day],
          axis="columns").set_axis(["year", "month", "day"], axis="columns")))
>>> out
       start        end anniversary
0 2008-02-11 2009-03-13  2009-02-11
1 2009-03-13 2010-03-13  2010-02-11
2 2010-03-13 2011-03-15  2011-02-11

Upvotes: 2

Shubham Sharma
Shubham Sharma

Reputation: 71689

You can use dt.year to get the year component of the datetime in start column then increment it by 1 and change the dtype to str. In the similar way, extract the month and day components from the anniversary column. Finally concat all the individual components and use pd.to_datetime to convert back to datetime:

year = df['start'].dt.year.add(1).astype(str)
month_day = df['anniversary'].dt.strftime('%m%d')

df['anniversary'] = pd.to_datetime(year + month_day, format='%Y%m%d')

>>> df
           start         end anniversary
index                                   
0     2008-02-11  2009-03-13  2009-02-11
1     2009-03-13  2010-03-13  2010-02-11
2     2010-03-13  2011-03-15  2011-02-11

Upvotes: 4

Related Questions