<p>这似乎是一个奇怪的错误,因为我从未见过azure中有这样的日志——不管怎样,除非有某种内置方法来处理这样的数据,否则我们需要手动解析它</p>
<p>我们将按<code>:</code>进行拆分,然后在重新创建时间增量字符串之前对数字进行四舍五入</p>
<p>我必须清楚地说,这不是一个真正的修复,因为你需要限定<code>1.05</code>是什么,是1小时x分钟吗</p>
<p>如果你不在乎上面的,那么下面的就行了</p>
<h2>方法1无精度,字符串格式</h2>
<pre><code>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
</code></pre>
<hr/>
<pre><code>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
</code></pre>
<p>如果您只需要几个小时,您可以使用<code>np.timedelta64</code>转换它</p>
<pre><code>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
</code></pre>
<hr/>
<h2>方法2更精确</h2>
<p>如果您的数据格式相同-即<code>Hours : Minutes : Seconds</code></p>
<p>我们可以堆叠并应用累积计数和映射元数据字段,以便在行级别使用我们的<code>pd.to_timedelta</code></p>
<pre><code>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
</code></pre>
<hr/>
<pre><code>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
</code></pre>
<p>最后,我们在行级别使用<code>apply</code>将每一行转换为其代表格式,并四舍五入到最接近的<code>n</code>秒。我选了10个</p>
<pre><code>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
</code></pre>