使用datetime.time进行比较和创建列 [英] Using datetime.time for comparison and column creation

查看:44
本文介绍了使用datetime.time进行比较和创建列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Pandas已有一段时间了,我确定这是一个愚蠢的问题。

I've been using Pandas for a while and I'm sure it's a dumb question.

我需要在有条件的数据框中创建一列到datetime.time。如果datetime.time< 12,在早晨列中填入内容,然后对下午和晚上进行相同的处理。

I need to create a column in a data frame which is conditional to the datetime.time. If datetime.time < 12, fill column with 'morning', then the same process to 'afternoon' and 'night'.

import datetime

b['time'] = ['01-01-2000 10:00:00', '01-01-2000 15:00:00', '01-01-2000 21:00:00']

b['time'].dt.time

(output)
1   10:00:00
2   15:00:00
3   21:00:00

b['time'].dt.time < 12 #example

TypeError: can't compare datetime.time to int

问题是:我无法将datetime.time与int比较。我该如何解决?

Question is: I can't compare datetime.time to int. How can I fix this?

非常感谢。

推荐答案

I认为您可以使用 cut numpy.searchsorted 以按箱分类标签:

I think you can use cut or numpy.searchsorted for labels by bins:

rng = pd.date_range('2017-04-03', periods=24, freq='H')
df = pd.DataFrame({'Date': rng})  

bins = [0, 5, 13, 17, 25]
labels = ['Morning','Afternoon','Evening','Night']
hours = df['Date'].dt.hour
df['bin'] = pd.cut(hours-5+24 *(hours<5),bins=bins,labels=labels,right=False)







bins = [-1,4,9,17,21]
labels = ['Night', 'Morning','Afternoon','Evening','Night']
df['bin1']  = np.array(labels)[np.array(bins).searchsorted(hours)-1]                     
print (df)
                  Date        bin       bin1
0  2017-04-03 00:00:00      Night      Night
1  2017-04-03 01:00:00      Night      Night
2  2017-04-03 02:00:00      Night      Night
3  2017-04-03 03:00:00      Night      Night
4  2017-04-03 04:00:00      Night      Night
5  2017-04-03 05:00:00    Morning    Morning
6  2017-04-03 06:00:00    Morning    Morning
7  2017-04-03 07:00:00    Morning    Morning
8  2017-04-03 08:00:00    Morning    Morning
9  2017-04-03 09:00:00    Morning    Morning
10 2017-04-03 10:00:00  Afternoon  Afternoon
11 2017-04-03 11:00:00  Afternoon  Afternoon
12 2017-04-03 12:00:00  Afternoon  Afternoon
13 2017-04-03 13:00:00  Afternoon  Afternoon
14 2017-04-03 14:00:00  Afternoon  Afternoon
15 2017-04-03 15:00:00  Afternoon  Afternoon
16 2017-04-03 16:00:00  Afternoon  Afternoon
17 2017-04-03 17:00:00  Afternoon  Afternoon
18 2017-04-03 18:00:00    Evening    Evening
19 2017-04-03 19:00:00    Evening    Evening
20 2017-04-03 20:00:00    Evening    Evening
21 2017-04-03 21:00:00    Evening    Evening
22 2017-04-03 22:00:00      Night      Night
23 2017-04-03 23:00:00      Night      Night

这篇关于使用datetime.time进行比较和创建列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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