您可以使用
total_seconds
用于转换
timedelta
到秒,然后计数
hours
,
minutes
dt.components
:
s = diff.dt.total_seconds().astype(int)
hours = s // 3600
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
a = hours.astype(str) + 'h ' + minutes.astype(str)
print (a)
0 1h 25
1 0h 41
2 0h 21
3 16h 41
4 4h 32
5 3h 1
6 1h 37
7 1h 13
8 1h 7
9 2h 33
10 714h 33
11 3h 50
12 1h 57
Name: Diff, dtype: object
Zero comment
解决:
hours = diff.dt.days * 24 + diff.dt.components.hours
minutes = diff.dt.components.minutes
a = hours.astype(str) + 'h ' + minutes.astype(str)
print (a)
0 1h 25m
1 0h 41m
2 0h 21m
3 16h 41m
4 4h 32m
5 3h 1m
6 1h 37m
7 1h 13m
8 1h 7m
9 2h 33m
10 18h 33m
11 3h 50m
12 1h 57m
dtype: object
a = pd.Series(['{0[0]}h {0[1]}m'.format(x) for x in zip(hours, minutes)])
print (a)
0 1h 25m
1 0h 41m
2 0h 21m
3 16h 41m
4 4h 32m
5 3h 1m
6 1h 37m
7 1h 13m
8 1h 7m
9 2h 33m
10 714h 33m
11 3h 50m
12 1h 57m
dtype: object
:
#13000 rows
df = pd.concat([df]*1000).reset_index(drop=True)
In [191]: %%timeit
...: hours = diff.dt.days * 24 + diff.dt.components.hours
...: minutes = diff.dt.components.minutes
...:
...: a = hours.astype(str) + 'h ' + minutes.astype(str)
...:
1 loop, best of 3: 483 ms per loop
In [192]: %%timeit
...: s = diff.dt.total_seconds().astype(int)
...:
...: hours = s // 3600
...: # remaining seconds
...: s = s - (hours * 3600)
...: # minutes
...: minutes = s // 60
...: # remaining seconds
...: seconds = s - (minutes * 60)
...:
...: a = hours.astype(str) + 'h ' + minutes.astype(str)
...:
10 loops, best of 3: 43.9 ms per loop
In [193]: %%timeit
...: hours = diff.dt.days * 24 + diff.dt.components.hours
...: minutes = diff.dt.components.minutes
...: s = pd.Series(['{0[0]}h {0[1]}m'.format(x) for x in zip(hours, minutes)])
...:
1 loop, best of 3: 465 ms per loop
#cá´Êá´
sá´á´á´á´
solution
In [194]: %%timeit
...: c = diff.dt.components[['days', 'hours', 'minutes']]
...: a = (c.days * 24 + c.hours).astype(str) + 'h ' + c.minutes.astype(str) + 'm'
...:
1 loop, best of 3: 208 ms per loop