python 条件语句得出新列,在条件语句中使用时间和数值创建分类列python

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

Condition - if time is between 05:00:00 and 19:00:00 and t_value > 0 & t_value <=13 then classify as "C" else "IC"

If time is not in the range then classify as NA

Example Input

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

Expected Output

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值