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'
最佳答案
除以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
关于python - Pandas :从timedelta中提取小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093199/