changing Years in a date column

Viewed 6483

I have a dataframe with first column of date.

import pandas as pd    
df = pd.DataFrame({'Date': ['8/4/2014','8/5/2014','8/14/2014','8/21/2014','8/23/2015','8/24/2015']})

I want to change all the 2014 to 2015 and 2015 to 2016.

I was looking at pandas.datetime, but it does not seem like it doesn't have such function. please help me out here. Thank you so much.

4 Answers

You can try this:

df['Date'] = pd.to_datetime(df['Date'])
df['Date'] = df['Date'].apply(lambda x: x.replace(year = x.year + 1))

You can also use pd.Timedelta

df['Date'] + pd.Timedelta(days = 365)

An alternative is the pd.DateOffset:

df['Date'] = df['Date'] + pd.DateOffset(years=1)

You should avoid apply. Use pd.offsets.Dateoffset. This gets calendar years correct, regardless of leap years.

df['Date'] = pd.to_datetime(df.Date) + pd.offsets.DateOffset(years=1)

Output:

        Date
0 2015-08-04
1 2015-08-05
2 2015-08-14
3 2015-08-21
4 2016-08-23
5 2016-08-24

Here is a simple string replacement without having to use datetime methods:

df['Date'].replace('2015', '2016', regex=True).replace('2014', '2015', regex=True)

This way you don't have to change all the years in the dataframe if that's a concern.

Use timedelta. You can add a day by '+ timedelta(days=1)'

Related