Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 734
elksie5000 Avatar asked Nov 21 '25 10:11

elksie5000


2 Answers

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]
like image 124
BENY Avatar answered Nov 24 '25 23:11

BENY


Try:

df.Date += pd.to_timedelta(df.Year - df.Date.dt.year, unit='Y')
like image 34
Quang Hoang Avatar answered Nov 24 '25 23:11

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!