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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With