计算 pandas 日期时间列的累积持续时间

编程入门 行业动态 更新时间:2024-10-24 10:26:20
本文介绍了计算 pandas 日期时间列的累积持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有以下熊猫数据框

Suppose I have the following pandas dataframe

df = pd.DataFrame ({'time': ['2014-05-01 18:47:05', '2014-05-01 18:47:06', '2014-05-02 18:47:08', '2014-05-02 18:47:10', '2014-05-02 18:47:11']}) df['time'] = pd.to_datetime(df['time'])

这给出了以下数据框

time 0 2014-05-01 18:47:05 1 2014-05-01 18:47:06 2 2014-05-02 18:47:08 3 2014-05-02 18:47:10 4 2014-05-02 18:47:11

我想添加另一列,以秒为单位计算时间列的持续时间

I would like to add another column that calculates the duration of the time column in seconds as follow

time duration 0 2014-05-01 18:47:05 0 1 2014-05-01 18:47:06 1 2 2014-05-02 18:47:08 3 3 2014-05-02 18:47:10 5 4 2014-05-02 18:47:11 6

显然,我可以进行一些循环并手动进行更改,但我怀疑这不是 Pythonic 的方法.Pandas 中是否有任何函数可以简化这个过程?

Obviously, I can do some looping and make a difference manually but I suspect this is not a pythonic way to this. Is there any function in pandas that would simplify this process?

推荐答案

这将使您获得以秒为单位的总差异(即也计算日期差异):

This will get you the total difference in seconds (i.e., counting differences in dates too):

df['duration'] = pd.to_timedelta( df['time'] - df['time'][0] ).astype('timedelta64[s]')

更多推荐

计算 pandas 日期时间列的累积持续时间

本文发布于:2023-10-27 15:32:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533800.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:持续时间   日期   时间   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!