从timedelta中提取分钟 - Python

4

我有一列时间差值,我希望创建一个额外的列,从时间差值列中提取小时和分钟。

df

time_delta          hour_minute
02:51:21.401000     2h:51min
03:10:32.401000     3h:10min
08:46:43.401000     08h:46min

这是我迄今为止尝试过的:

df['rh'] = df.time_delta.apply(lambda x: round(pd.Timedelta(x).total_seconds() \
                          % 86400.0 / 3600.0) )

很抱歉,我不太确定如何提取只包含分钟而不包括小时的部分。


你的 time_delta 列的 dtype 是什么?你能打印出 df['time_delta'].dtypes 的输出吗? - Abhilash Awasthi
这个回答解决了你的问题吗?格式化timedelta对象 - Stefan
2个回答

5

使用 Series.dt.components 获取小时和分钟并将其连接在一起:

td = pd.to_timedelta(df.time_delta).dt.components
df['rh'] = (td.hours.astype(str).str.zfill(2) + 'h:' + 
            td.minutes.astype(str).str.zfill(2) + 'min')
print (df)
        time_delta hour_minute         rh
0  02:51:21.401000    2h:51min  02h:51min
1  03:10:32.401000    3h:10min  03h:10min
2  08:46:43.401000   08h:46min  08h:46min

如果可能的小时值更多,例如24小时,那么也需要添加天数:

print (df)
        time_delta hour_minute
0  02:51:21.401000    2h:51min
1  03:10:32.401000    3h:10min
2  28:46:43.401000   28h:46min

td = pd.to_timedelta(df.time_delta).dt.components
print (td)
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     0      2       51       21           401             0            0
1     0      3       10       32           401             0            0
2     1      4       46       43           401             0            0

df['rh'] = ((td.days * 24 + td.hours).astype(str).str.zfill(2) + 'h:' + 
            td.minutes.astype(str).str.zfill(2) + 'min')
print (df)

        time_delta hour_minute         rh
0  02:51:21.401000    2h:51min  02h:51min
1  03:10:32.401000    3h:10min  03h:10min
2  28:46:43.401000   28h:46min  28h:46min

1

另请参见this post,其中定义了该函数

def strfdelta(tdelta, fmt):
    d = {"days": tdelta.days}
    d["hours"], rem = divmod(tdelta.seconds, 3600)
    d["minutes"], d["seconds"] = divmod(rem, 60)
    return fmt.format(**d)

然后,例如。
strfdelta(pd.Timedelta('02:51:21.401000'), '{hours}h:{minutes}min')

给出了'2h:51min'

对于您的完整数据帧。

df['rh'] = df.time_delta.apply(lambda x: strfdelta(pd.Timedelta(x), '{hours}h:{minutes}min'))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接