【问题标题】:Pandas: extract hour from timedelta熊猫:从 timedelta 中提取小时
【发布时间】:2018-08-30 09:09:45
【问题描述】:

This answer 解释了如何在 Pandas 中将整数转换为每小时时间步长。我需要做相反的事情。

我的数据框df1

   A
0  02:00:00
1  01:00:00
2  02:00:00
3  03:00:00

我预期的数据框df1

   A         B
0  02:00:00  2
1  01:00:00  1
2  02:00:00  2
3  03:00:00  3

我正在尝试什么:

df1['B'] = df1['A'].astype(int)

这失败了,因为: TypeError: cannot astype a timedelta from [timedelta64[ns]] to [int32]

最好的方法是什么?

编辑

如果我尝试df['B'] = df['A'].dt.hour,那么我会得到: AttributeError: 'TimedeltaProperties' object has no attribute 'hour'

【问题讨论】:

    标签: python pandas delta timestep


    【解决方案1】:

    您可以使用dt.components 并访问小时列:

    In[7]:
    df['B'] = df['A'].dt.components['hours']
    df
    
    Out[7]: 
             A  B
    0 02:00:00  2
    1 01:00:00  1
    2 02:00:00  2
    3 03:00:00  3
    

    timedelta 组件将每个组件作为一列返回:

    In[8]:
    df['A'].dt.components
    
    Out[8]: 
       days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
    0     0      2        0        0             0             0            0
    1     0      1        0        0             0             0            0
    2     0      2        0        0             0             0            0
    3     0      3        0        0             0             0            0
    

    【讨论】:

    • 谢谢 - 这个细分非常有用。我现在不需要它,但我会把它留给其他人将来受益。
    • 如果有人只想要几分钟、几毫秒等,这可能很有用。
    【解决方案2】:

    除以np.timedelta64(1, 'h'):

    df1['B'] = df1['A'] / np.timedelta64(1, 'h')
    print (df1)
             A    B
    0 02:00:00  2.0
    1 01:00:00  1.0
    2 02:00:00  2.0
    3 03:00:00  3.0
    

    【讨论】:

      【解决方案3】:

      两种解决方案 - dt.componentsnp.timedelta64 - 都很有用。但是 np.timedelta64 是 (1) 比 dt.components 快得多(很高兴知道,尤其是对于大型数据帧) (2,正如@Sam Chats 所指出的)还考虑了天数的差异。

      时间比较:

      import pandas as pd
      import numpy as np
      
      dct = { 
            'date1': ['08:05:23', '18:07:20', '08:05:23'],
            'date2': ['09:15:24', '22:07:20', '08:54:01']
            }
      df = pd.DataFrame(dct)
      df['date1'] = pd.to_datetime(df['date1'], format='%H:%M:%S')
      df['date2'] = pd.to_datetime(df['date2'], format='%H:%M:%S')
      df['delta'] = df['date2']-df['date1']
      
      %timeit df['np_h'] = (df['delta'] / np.timedelta64(1,'h')).astype(int)
      %timeit df['td_h'] = df['delta'].dt.components['hours']
      
      Output:
      1000 loops, best of 3: 484 µs per loop
      1000 loops, best of 3: 1.43 ms per loop
      

      【讨论】:

      • 我不认为 components 执行 dt.components['days']*24 乘法。它只是从TimedeltaProperties 对象返回hours 组件。
      猜你喜欢
      • 2019-05-21
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 2020-06-02
      • 1970-01-01
      • 2020-06-24
      相关资源
      最近更新 更多