简体   繁体   English

将日期时间列的年份更改为另一列的年份 + 1

[英]change year of datetime column by the year of another column + 1

I want to calculate the anniversary column by this way: keep the date and month, and change the year to the same year as start column + 1我想通过这种方式计算周年纪念列:保留日期和月份,并将年份更改为与开始列相同的年份+1

This is my pandas dataframe:这是我的 pandas dataframe:

| index |   start       |      end       |     anniversary|   
| ----- | -----------   | -------------- | -------------- | 
| 0     |   2008-02-11  |    2009-03-13  |   2009-02-11   |     
| 1     |   2009-03-13  |    2010-03-13  |   2009-02-11   |     
| 2     |   2010-03-13  |    2011-03-15  |   2009-02-11   |     

What i want to get:我想得到什么:

| index |   start       |      end       |     anniversary|   
| ----- | -----------   | -------------- | -------------- | 
| 0     |   2008-02-11  |    2009-03-13  |   2009-02-11   |     
| 1     |   2009-03-13  |    2010-03-13  |   2010-02-11   |     
| 2     |   2010-03-13  |    2011-09-19  |   2011-02-11   |      

You can use dt.year to get the year component of the datetime in start column then increment it by 1 and change the dtype to str .您可以使用dt.yearstart列中获取日期时间的年份部分,然后将其递增1并将dtype更改为str In the similar way, extract the month and day components from the anniversary column.以类似的方式,从anniversary列中提取monthday部分。 Finally concat all the individual components and use pd.to_datetime to convert back to datetime :最后连接所有单独的组件并使用pd.to_datetime转换回datetime

year = df['start'].dt.year.add(1).astype(str)
month_day = df['anniversary'].dt.strftime('%m%d')

df['anniversary'] = pd.to_datetime(year + month_day, format='%Y%m%d')

>>> df
           start         end anniversary
index                                   
0     2008-02-11  2009-03-13  2009-02-11
1     2009-03-13  2010-03-13  2010-02-11
2     2010-03-13  2011-03-15  2011-02-11

Just for fun an one-liner implementation:只是为了好玩单行实现:

out = df.assign(anniversary=pd.to_datetime(pd.concat(
          [df["start"].dt.year + 1, df["anniversary"].dt.month, df["anniversary"].dt.day],
          axis="columns").set_axis(["year", "month", "day"], axis="columns")))
>>> out
       start        end anniversary
0 2008-02-11 2009-03-13  2009-02-11
1 2009-03-13 2010-03-13  2010-02-11
2 2010-03-13 2011-03-15  2011-02-11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM