elksie5000
elksie5000

Reputation: 7782

How to map year of datetime column from another column in pandas

I have a dataframe in the following format. The year is wrong in the Date column I want to be able to replace

   Date         Year
0  2013-04-13   2019
1  2013-04-13   2019

What's the best way of mapping the Year into the datetime column?

Upvotes: 2

Views: 733

Answers (2)

BENY
BENY

Reputation: 323396

Using replace

df.apply(lambda x :x.Date.replace(year=x.Year),1)
Out[307]: 
0   2019-04-13
1   2019-04-13
dtype: datetime64[ns]

Upvotes: 5

Quang Hoang
Quang Hoang

Reputation: 150825

Try:

df.Date += pd.to_timedelta(df.Year - df.Date.dt.year, unit='Y')

Upvotes: 3

Related Questions