Python-取与列中第一个日期的时差 [英] Python - take the time difference from the first date in a column

查看:53
本文介绍了Python-取与列中第一个日期的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于date列,我想创建另一个列diff,该列比较从第一个日期算起有多少天.

Given the date column, I want to create another column diff that count how many days apart from the first date.

date                    diff
2011-01-01 00:00:10      0
2011-01-01 00:00:11      0.000011 days
2011-02-01 00:00:11      30.000011 days 
2013-02-01 00:00:11      395.000011 days
2014-02-01 00:00:11      760.000011 days

日期为日期时间.到目前为止我尝试过的:

Dates are in datetime. What I tried so far:

df = df.sort_values(['date'], ascending=True)
df.set_index('date', inplace = True)
first = df.index[0]
df['diff'] = (first - df.index.shift()).fillna(0)

推荐答案

您可以尝试

df['diff'] = df.date - df.date.min()

df
                 date               diff
0 2011-01-01 00:00:10    0 days 00:00:00
1 2011-01-01 00:00:11    0 days 00:00:01
2 2011-02-01 00:00:11   31 days 00:00:01
3 2013-02-01 00:00:11  762 days 00:00:01
4 2014-02-01 00:00:11 1127 days 00:00:01

这篇关于Python-取与列中第一个日期的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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