pandas 计算时差 [英] Pandas calculate time difference

查看:97
本文介绍了 pandas 计算时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有日期数据,我试图在这些数据中计算连续行之间的秒数.

I have date data where I am trying to calculate different in second between successive rows.

我的数据

date
0   2014-05-01 18:47:05
1   2014-05-01 18:47:25
2   2014-05-02 18:47:45
3   2014-05-02 18:48:05
4   2014-05-02 18:48:55

这是我尝试的方法:

df['time_diff'] = (df['date']-df['date'].shift()).fillna(0)
df['second'] = df['time_diff'].apply(lambda x: x  / np.timedelta64(1,'s')).astype('int64') % (24*60)

但是我的第二列仅显示时间的秒部分之间的差异.不是整个时间.

But my second column only shows difference between seconds section of the time. Not from entire time.

    date                time_diff       second
0   2014-05-01 18:47:05 0 days 00:00:00 0
1   2014-05-01 18:47:25 0 days 00:00:20 20
2   2014-05-02 18:47:45 1 days 00:00:20 20
3   2014-05-02 18:48:05 0 days 00:00:20 20
4   2014-05-02 18:48:55 0 days 00:00:50 50

推荐答案

使用diffdt.seconds

df.date.diff().dt.seconds


df.assign(seconds=df.date.diff().dt.seconds)

                 date  seconds
0 2014-05-01 18:47:05      NaN
1 2014-05-01 18:47:25     20.0
2 2014-05-02 18:47:45     20.0
3 2014-05-02 18:48:05     20.0
4 2014-05-02 18:48:55     50.0

这篇关于 pandas 计算时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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