如何通过使用PANDAS向今天的日期添加相应的天数列来创建新的日期列 [英] How to create a new column of dates by adding a corresponding column of days to today's date using PANDAS

查看:800
本文介绍了如何通过使用PANDAS向今天的日期添加相应的天数列来创建新的日期列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据框df的最后一列如下:

The final column of my dataframe df looks like:

    ...   Days till Service
0   ...                   0
1   ...                  28
2   ...                   7
3   ...                  54
4   ...                   0
5   ...                   6
6   ...                  28
7   ...                   0
8   ...                  16
9   ...                 200

问题:

我想创建一个名为Predicted Service Date的新列,我可以在其中添加Days till Service到今天的日期.我该怎么办?

I want to create a new column named Predicted Service Date, where I can add the Days till Service on to today's date. How can I do this?

理想的输出:

如果今天的日期是16/04/2018,则df应该如下所示:

If today's date is 16/04/2018, then the df should look as the following:

    ...   Days till Service   Predicted Service Date
0   ...                   0               16/04/2018
1   ...                  28               14/05/2018
2   ...                   7               23/04/2018
3   ...                  54               09/06/2018
4   ...                   0               16/04/2018
5   ...                   6               22/04/2018
6   ...                 365               16/04/2019
7   ...                   0               16/04/2018
8   ...                  16               02/05/2018
9   ...                 200               02/11/2018

推荐答案

使用

Using pd.to_timedelta, you can convert df['Days till Service'] to timedeltas, then add them to today's date:

df['Predicted Service Date'] = \
    pd.to_datetime('today') + pd.to_timedelta(df['Days till Service'], unit='D')

这篇关于如何通过使用PANDAS向今天的日期添加相应的天数列来创建新的日期列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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