这个答案解释了如何在 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'
您可以使用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
除以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
这两种解决方案(dt.components或np.timedelta64(都很有用。但是 np.timedelta64 是 (1(比DT.components快得多(特别是对于大型数据帧,很高兴知道( (2,正如@Sam聊天所指出的(也考虑了天数的差异。
对于时间比较:
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
或者除以pd.Timedelta(1, 'h')
:
df1['B'] = df1['A'] / pd.Timedelta(1, 'h')
结果是浮动。
https://pandas.pydata.org/docs/reference/api/pandas.Timedelta.html