本文介绍了计算 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 日期时间列的累积持续时间
发布评论