替换 pandas.datetime 列中的年份 [英] Replace the year in pandas.datetime column

查看:55
本文介绍了替换 pandas.datetime 列中的年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 pd.to_datetime() 转换的日期列的数据框.当我检查数据时,我发现这些日期中很少有提到年份为 2216 的日期,应该是 2016 年.请您帮我将这些日期的年份从 2216 更改为 2016

I have a dataframe with a date column converted using pd.to_datetime(). When I inspected the data I found few of these dates with year mentioned as 2216, which should have been 2016. Can you please help me change the year for these dates from 2216 to 2016

     Date
0   2216-12-21
1   2216-12-23
2   2216-01-31
3   2016-12-23
4   2216-12-27
5   2216-12-25
6   2016-12-23

我尝试使用 str.replace

I tried using str.replace

 df['Date'] = df['Date'].str.replace("2216","2016")

但出现以下错误

 Can only use .str accessor with string values, which use np.object_ dtype in pandas

提前致谢

推荐答案

使用:

df['Date'] = df['Date'].mask(df['Date'].dt.year == 2216, 
                             df['Date'] + pd.offsets.DateOffset(year=2016))
print (df)
        Date
0 2016-12-21
1 2016-12-23
2 2016-01-31
3 2016-12-23
4 2016-12-27
5 2016-12-25
6 2016-12-23

为了更好的性能:

df['Date'] = df['Date'].mask(df['Date'].dt.year == 2216, df['Date'] - 
                                                         pd.to_timedelta(200, unit='y') + 
                                                         pd.to_timedelta(12, unit='h'))
print (df)
        Date
0 2016-12-21
1 2016-12-23
2 2016-01-31
3 2016-12-23
4 2016-12-27
5 2016-12-25
6 2016-12-23

这篇关于替换 pandas.datetime 列中的年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆