【发布时间】:2018-11-29 01:57:39
【问题描述】:
我有一个 df 和一个 column 以秒为单位显示时间。我想将它们转换为hh:mm 或hh:mm:ss。
如果时间超过标准的 24 小时时间,我仍然希望它位于 hh:mm:ss。不是'n' days hh:mm:ss。
举个例子:
import pandas as pd
import numpy as np
import datetime
ts1 = ['21000', np.nan, '40000', np.nan, '49000', '100000']
ts2 = [0, 2, 'yy', 3, 'yy', 'yy']
ts3 = [0, 2, np.nan, 3, 4, np.nan]
d = {'X': ts1, 'Y': ts2, 'Z': ts3}
df = pd.DataFrame(data=d)
输出:
X Y Z
0 21000 0 0.0
1 NaN 2 2.0
2 40000 yy NaN
3 NaN 3 3.0
4 49000 yy 4.0
5 100000 yy NaN
我可以在单个 string 上使用:
t = str(datetime.timedelta(seconds=21000))
输出时间:
5:50:00
但是我如何将相同的函数传递给一整列呢?
#t_col = str(datetime.timedelta(seconds=df['ts1']))
预期输出:
X Y Z
0 5:50:00 0 0.0
1 NaN 2 2.0
2 11:06:40 yy NaN
3 Nan 3 3.0
4 13:36:40 yy 4.0
5 27:46:40 yy NaN
【问题讨论】:
标签: python pandas time timedelta