python - Pandas :从timedelta中提取小时

标签 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'

最佳答案

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

相关文章:

python - 如何使用每个选择的模板覆盖 ModelChoiceField/ModelMultipleChoiceField 默认小部件

python - 未知后端 : No event loop integration for u'inline' when enable inline matplotlib in emacs python notebook

python - Python 中的一个令人困惑的案例

python - 在 Python 中创建连续年份月份的列表

java - Dropbox v2 文件 ID 作为增量的一部分

python - 使用 python ast 中 ._field 属性中存储的值

python - pandas 数据框标签列编码

python - 重命名 Pandas 数据框中的选定列

测试神经网络——训练后

Linux - mkstemp64 如何创建隐藏文件,我如何在文件系统中看到它