繁体   English   中英

从 Pandas Timedelta 获取总小时数?

[英]Get total number of hours from a Pandas Timedelta?

如何获得 Pandas timedelta 中的总小时数?

例如:

>>> td = pd.Timedelta('1 days 2 hours')
>>> td.get_total_hours()
26

注意:根据文档, .hours属性将返回 hours组件

>>> td.hours
2

只需找出 1 小时的timedelta有多少适合它:

import numpy as np

>> td / np.timedelta64(1, 'h')
26.0

试着说明为什么大熊猫返回 2 小时。

import pandas as pd

td = pd.Timedelta('1 days 2 hours')

td.components

Out[45]: Components(days=1, hours=2, minutes=0, seconds=0, milliseconds=0, microseconds=0, nanoseconds=0)

td / pd.Timedelta('1 hour')

Out[46]: 26.0

我以秒为单位获得时间增量并将其除以 3600 以获得小时

round(td.total_seconds() / 3600)

当我在 jupyter notebook 中测试时,这种方法运行得更快

%timeit td / np.timedelta64(1, 'h') 
The slowest run took 19.10 times longer than the fastest. This could mean that an intermediate result is being cached. 
100000 loops, best of 3: 4.58 µs per loop

%timeit round(td.total_seconds() / 3600)
The slowest run took 18.08 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 401 ns per loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM