pandas :从 timedelta 中提取小时 [英] Pandas: extract hour from timedelta

查看:161
本文介绍了 pandas :从 timedelta 中提取小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个答案 解释了如何在 Pandas 中将整数转换为每小时的时间步长.我需要做相反的事情.

This answer explains how to convert integers to hourly timesteps in Pandas. I need to do the opposite.

我的数据框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: 不能从 [timedelta64[ns]] 到 [int32] 输入时间增量

最好的方法是什么?

编辑

如果我尝试 df['B'] = df['A'].dt.hour,那么我得到:AttributeError: 'TimedeltaProperties' 对象没有属性 'hour'

If I try df['B'] = df['A'].dt.hour, then I get: 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

这篇关于 pandas :从 timedelta 中提取小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆