熊猫:从timedelta中提取小时

时间:2018-08-30 09:09:46

标签: python pandas delta timestep

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'

3 个答案:

答案 0 :(得分:3)

除以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

答案 1 :(得分:3)

您可以使用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 :(得分:-1)

两个解决方案- dt.components np.timedelta64 -都很有用。只是np.timedelta64比dt.components快得多(特别是对于大型数据帧,要知道这一点):

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

而且,正如@EdChum所指出的,dt.components['hours']仅返回小时数<24的值,对于这个问题,这确实不是问题。但是对于增量> 24小时必须使用dt.components['days']*24+dt.components['hours']的完整日期(这会使处理时间加倍)。