Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing Years in a date column

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.

like image 295
Yun Tae Hwang Avatar asked Dec 03 '22 10:12

Yun Tae Hwang


2 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)
like image 194
Mohit Motwani Avatar answered Dec 22 '22 19:12

Mohit Motwani


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
like image 23
ALollz Avatar answered Dec 22 '22 19:12

ALollz