pandas :四舍五入到最近的小时 [英] Pandas: Rounding to nearest Hour

查看:91
本文介绍了 pandas :四舍五入到最近的小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列带有时间戳的

 start_time: 
 0    2016-06-04 05:18:49
 1    2016-06-04 06:50:12
 2    2016-06-04 08:16:02
 3    2016-06-04 15:05:13
 4    2016-06-04 15:24:25

我想在start_time列上使用一个函数来取整分钟> = 30到下一个小时。

I want use a function on the start_time column to round minutes >= 30 to the next hour.

 def extract_time(col):
      time = col.strftime('%H:%M')
      min= int(time.strip(':')[1])
      hour= int(time.strip(':')[0])
      if min >= 30:
           return hour + 1
      return hour

然后我想创建一个新的小时列,并使用四舍五入的小时数:

Then I want to create a new columns 'hour', with the rounded hours:

 df['hour'] = df['start_time'].apply(extract_time)

而不是使用四舍五入后的时间,我得到以下信息:

Instead of getting getting an 'hour' column with the rounded hours, I am getting the below:

 0    <function extract_hour at 0x128722b90>
 1    <function extract_hour at 0x128722b90>
 2    <function extract_hour at 0x128722b90>
 3    <function extract_hour at 0x128722b90>
 4    <function extract_hour at 0x128722b90>


推荐答案

您可以使用以下矢量化解决方案:

you can use the following vectorized solution:

In [30]: df['hour'] = df['start_time'].dt.round('H').dt.hour

In [31]: df
Out[31]:
           start_time  hour
0 2016-06-04 05:18:49     5
1 2016-06-04 06:50:12     7
2 2016-06-04 08:16:02     8
3 2016-06-04 15:05:13    15
4 2016-06-04 15:24:25    15

这篇关于 pandas :四舍五入到最近的小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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