gpt4 book ai didi

python - Python Pandas 中的时间格式化

转载 作者:行者123 更新时间:2023-11-28 17:32:24 26 4
gpt4 key购买 nike

我有一个时间格式为 mm:ss.0 的 Excel 文件。我在 Excel 中将其格式化为 [h]:mm:ss;@。这怎么能在 Pandas 中完成?

Time : 58:44.1 in mm:ss.0 格式在 Excel 中以 [h]:mm:ss;@ 格式产生结果 7:58:44格式化后。

例如:

Input      Desired Output
58:44.1 7:58:44
07:53.3 8:07:53
46:59.6 9:47:00
20:14.0 10:20:14
50:58.7 11:50:59
19:50.0 12:19:50
41:53.5 13:41:53

最佳答案

您可以使用矢量化 str 对字符串进行切片方法,然后使用 to_datetime 构造 datetime由此传递格式字符串并向其添加 TimedeltaIndex,然后使用 dt.time 访问 time 组件:

In [199]:
df['Desired Output'] = (pd.to_datetime(df['Input'].str[:-2], format='%M:%S') + pd.TimedeltaIndex(np.arange(7, 7 + len(df)), 'h')).dt.time
df

Out[199]:
Input Desired Output
0 58:44.1 07:58:44
1 07:53.3 08:07:53
2 46:59.6 09:46:59
3 20:14.0 10:20:14
4 50:58.7 11:50:58
5 19:50.0 12:19:50
6 41:53.5 13:41:53

您可以看到 Desired Output 的 dtype 不是 datetime.time:

In [201]:
df['Desired Output'].iloc[0]

Out[201]:
datetime.time(7, 58, 44)

关于python - Python Pandas 中的时间格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33411597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com