python - 从 timedelta 中提取分钟 - Python
问题描述
我有一个带有 timedelta 的列,我想创建一个额外的列,从 timedelta 列中提取小时和分钟。
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) )
不幸的是,我不太确定如何在没有包含的情况下提取分钟。小时
解决方案
用于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
推荐阅读
- c# - 使用 C# 使用 .NET Framework HttpWebRequest 自定义代理服务器标头
- mysql - mysql - how to save results from DESCRIBE table into table
- python - 如何点击一个div?
- string - 如何从一对输入字符串创建组合对(二元组)?
- html - 下载 angular 8 a txt
- javascript - 如何使用 this.props.history 发送的数据?
- amazon-web-services - AWS IOT 节点开发工具包的服务质量
- c# - 在 Xamarin 中更改 UWP Listview 选定项背景颜色
- java - 为什么客户端无法在这个 java nio 程序中连接到服务器?
- powerquery - 如何设置查询的源名称是另一个查询的值?