在条件语句中使用时间和数值创建分类列python [英] Using time and numerical value in conditional statements to create categorical column python

查看:92
本文介绍了在条件语句中使用时间和数值创建分类列python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用时间和数值执行if语句以创建新列分类列

I'm trying to execute if statement using time and numerical value to make a new column categorical column

条件-如果时间介于05:00:00和19:00:00,并且t_value> 0& t_value< = 13然后分类为 C,否则分类为 IC

如果时间不在范围内然后分类为NA

示例输入

                   t_value 
2020-05-17 00:00:00 0     
2020-05-17 01:00:00 0
2020-05-17 02:00:00 0
2020-05-17 03:00:00 0
2020-05-17 04:00:00 0
2020-05-17 05:00:00 0
2020-05-17 06:00:00 0
2020-05-17 07:00:00 8
2020-05-17 08:00:00 9
2020-05-17 09:00:00 10
2020-05-17 10:00:00 11
2020-05-17 11:00:00 12 

我不确定在这方面采取的方法

I'm unsure of the approach to take in this regard

预期产量

                t_value  C/IC
2020-05-17 00:00:00 0    NA
2020-05-17 01:00:00 0    NA
2020-05-17 02:00:00 0    NA
2020-05-17 03:00:00 0    NA
2020-05-17 04:00:00 0    NA
2020-05-17 05:00:00 0    IC
2020-05-17 06:00:00 0    IC
2020-05-17 07:00:00 8    C
2020-05-17 08:00:00 9    C
2020-05-17 09:00:00 10   C
2020-05-17 10:00:00 11   C
2020-05-17 11:00:00 12   C


推荐答案

#convert to datetime index
df.index = pd.to_datetime(df.index)

#get condition for time boundary
cond1 = df.between_time( '05:00:00', '19:00:00')

print(cond1.index)
DatetimeIndex(['2020-05-17 05:00:00', '2020-05-17 06:00:00',
               '2020-05-17 07:00:00', '2020-05-17 08:00:00',
               '2020-05-17 09:00:00', '2020-05-17 10:00:00',
               '2020-05-17 11:00:00'],
              dtype='datetime64[ns]', freq=None)

#get index to match the t_value conditions

#indices that match time boundary, but not t_value boundary
ic = cond1.loc[~(cond1.t_value.gt(0)) & (cond1.t_value.le(13))].index

#indices that match time boundary and t_value boundary
c = cond1.loc[(cond1.t_value.gt(0)) & (cond1.t_value.le(13))].index

#assign value
df.loc[c,'C/IC'] = "C"
df.loc[ic,'C/IC'] = "IC"

print(df)

    t_value C/IC
2020-05-17 00:00:00 0   NaN
2020-05-17 01:00:00 0   NaN
2020-05-17 02:00:00 0   NaN
2020-05-17 03:00:00 0   NaN
2020-05-17 04:00:00 0   NaN
2020-05-17 05:00:00 0   IC
2020-05-17 06:00:00 0   IC
2020-05-17 07:00:00 8   C
2020-05-17 08:00:00 9   C
2020-05-17 09:00:00 10  C
2020-05-17 10:00:00 11  C
2020-05-17 11:00:00 12  C

这篇关于在条件语句中使用时间和数值创建分类列python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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