python - Pandas 计算时差

标签 python pandas

我有日期数据,我试图计算连续行之间的秒数差异。

我的数据

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)

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

    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

关于python - Pandas 计算时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088123/

相关文章:

python - 在 contains 方法中使用精确匹配正则表达式

python - 格式化字符串 (%s) 返回 TypeError : a float is required

python - Discord.py - 消息,只有一个用户可以在服务器中看到

numpy - 从 txt 文件计算平均值、标准差的有效方法

python - 删除 Pandas 列中每一行的空格后的字符

python - 使用 .loc 访问器的 pandas 日期时间索引的 bool 掩码

Python:使用变量作为 CSV 中的查找引用并返回值

Python 对两个数字之间的元素求和

Python statsmodel 稳健线性回归 (RLM) 异常值选择

python - 使用Python进行CSV数据分析