2 回答

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個(gè)贊
根據(jù)數(shù)據(jù)分析,我可以得出結(jié)論,hh 部分的小數(shù)位實(shí)際上是天。示例 2.4:30:30 = 2 天 4 小時(shí) 30 分鐘 30 秒。
def cleanhours(x):
hms=x.split(":")
dh=hms[0].split(".")
if len(dh)>1:
hms[0]=str(int(dh[-1])+24*int(dh[-2]))
hms[2] = hms[2].split(".")[0]
return int(hms[0])+int(hms[1])/60.0+int(hms[2])/3600.0
# return ":".join(hms)

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
似乎是一個(gè)奇怪的錯(cuò)誤,因?yàn)槲覐奈匆娺^像這樣來自 azure 的任何日志 - 無論如何,除非有一些內(nèi)置方法來處理這樣的數(shù)據(jù),否則我們將需要手動解析它。
在重新創(chuàng)建時(shí)間增量字符串之前,我們將拆分:然后舍入數(shù)字。
我必須明確地說,這不是真正的解決方法,因?yàn)槟枰薅ㄊ裁?.05是 1 小時(shí)零 x 分鐘?
如果您不關(guān)心以上內(nèi)容,那么以下內(nèi)容應(yīng)該有效。
方法 1 無精度,字符串格式。
print(df)
Duration
0 1.05:27:39.9470724
1 21:17.7
2 21:41.4
3 1.02:42:37.1136811
4 21:17.2
df['DurationFixed'] = pd.to_timedelta(df['Duration'].str.split(':',expand=True)\
.stack()\
.astype(float)\
.round()\
.astype(int).astype(str).unstack(1).fillna('00').agg(':'.join,axis=1),
unit='s')
print(df)
Duration DurationFixed
0 1.05:27:39.9470724 01:27:40
1 21:17.7 21:18:00
2 21:41.4 21:41:00
3 1.02:42:37.1136811 01:42:37
4 21:17.2 21:17:00
如果你只想要幾個(gè)小時(shí),你可以使用np.timedelta64
import numpy as np
df['DurationFixed'] / np.timedelta64(1,'h')
0 1.461111
1 21.300000
2 21.683333
3 1.710278
4 21.283333
Name: DurationFixed, dtype: float64
方法 2 更精確。
如果您的數(shù)據(jù)格式相同 - 即Hours : Minutes : Seconds
我們可以堆疊并應(yīng)用累積計(jì)數(shù)并映射元數(shù)據(jù)字段以pd.to_timedelta在行級別使用我們的。
s = df['Duration'].str.split(':',expand=True)\
.stack()\
.astype(float).to_frame('time_delta')
print(s)
time_delta
0 0 1.050000
1 27.000000
2 39.947072
1 0 21.000000
1 17.700000
2 0 21.000000
1 41.400000
3 0 1.020000
1 42.000000
2 37.113681
4 0 21.000000
1 17.200000
s['metadata'] = s.groupby(level=0).cumcount().map({0 : 'h', 1 : 'm', 2 : 's' })
print(s)
time_delta metadata
0 0 1.050000 h
1 27.000000 m
2 39.947072 s
1 0 21.000000 h
1 17.700000 m
2 0 21.000000 h
1 41.400000 m
3 0 1.020000 h
1 42.000000 m
2 37.113681 s
4 0 21.000000 h
1 17.200000 m
apply最后,我們在行級別使用 an將每一行轉(zhuǎn)換為它的 repective 格式并四舍五入到最接近的n秒數(shù)。我選了10個(gè)。
df['DurationPrecise'] = s.apply(lambda x : pd.to_timedelta(x.time_delta,
x.metadata,errors='coerce'),axis=1)\
.groupby(level=0).sum().dt.round('10s')
print(df)
Duration DurationFixed DurationPrecise
0 1.05:27:39.9470724 01:27:40 01:30:40
1 21:17.7 21:18:00 21:17:40
2 21:41.4 21:41:00 21:41:20
3 1.02:42:37.1136811 01:42:37 01:43:50
4 21:17.2 21:17:00 21:17:10
添加回答
舉報(bào)