如何在 pandas 的日期栏中添加年份 [英] How to add a year to a column of dates in pandas

查看:139
本文介绍了如何在 pandas 的日期栏中添加年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在熊猫数据框中的日期列中添加年份,但是当我使用 pd.to_timedelta 时,我会得到额外的小时数&分钟。我知道我可以获取更新的时间并缩短时间,但是我觉得必须有一种方法可以精确地增加一年。我的尝试如下:

I am attempting to add a year to a column of dates in a pandas dataframe, but when I use pd.to_timedelta I get additional hours & minutes. I know I could take the updated time and truncate the hours, but I feel like there must be a way to add a year precisely. My attempt as follows:

import pandas as pd
dates = pd.DataFrame({'date':['20170101','20170102','20170103']})
dates['date'] = pd.to_datetime(dates['date'], format='%Y%m%d')
dates['date2'] = dates['date'] +  pd.to_timedelta(1, unit='y')
dates

收益率:

Out[1]: 
    date        date2
0   2017-01-01  2018-01-01 05:49:12
1   2017-01-02  2018-01-02 05:49:12
2   2017-01-03  2018-01-03 05:49:12

如何添加一年而不添加05:49:12 HH :mm:ss?

How can I add a year without adding 05:49:12 HH:mm:ss?

推荐答案

In [99]: dates['date'] + pd.offsets.DateOffset(years=1)
Out[99]:
0   2018-01-01
1   2018-01-02
2   2018-01-03
Name: date, dtype: datetime64[ns]

le年检查:

In [100]: pd.to_datetime(['2011-02-28', '2012-02-29']) + pd.offsets.DateOffset(years=1)
Out[100]: DatetimeIndex(['2012-02-28', '2013-02-28'], dtype='datetime64[ns]', freq=None)

这篇关于如何在 pandas 的日期栏中添加年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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