【问题标题】:Get total number of hours from a Pandas Timedelta?从 Pandas Timedelta 获取总小时数?
【发布时间】:2015-09-25 19:01:53
【问题描述】:

如何获取 Pandas 时间增量中的总小时数?

例如:

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

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

>>> td.hours
2

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    只需找出 1 小时内有多少 timedeltas 适合它:

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

    【讨论】:

    • 我更喜欢pd.Timedelta(hours=1),因为 OP 已经在使用 pandas。
    • 想知道为什么没有 Timedelta.hours 属性。
    【解决方案2】:

    试着说明为什么 pandas 会返回 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
    

    【讨论】:

      【解决方案3】:

      我得到了以秒为单位的时间增量,然后除以 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-11
        • 2022-01-19
        • 2020-09-01
        • 2014-06-17
        相关资源
        最近更新 更多