Use cut
or custom function with and
and also changed <
to >
and >
to <=
and also for each value add return
:
prods = pd.DataFrame({'hour':range(1, 25)})
b = [0,4,8,12,16,20,24]
l = ['Late Night', 'Early Morning','Morning','Noon','Eve','Night']
prods['session'] = pd.cut(prods['hour'], bins=b, labels=l, include_lowest=True)
def f(x):
if (x > 4) and (x <= 8):
return 'Early Morning'
elif (x > 8) and (x <= 12 ):
return 'Morning'
elif (x > 12) and (x <= 16):
return'Noon'
elif (x > 16) and (x <= 20) :
return 'Eve'
elif (x > 20) and (x <= 24):
return'Night'
elif (x <= 4):
return'Late Night'
prods['session1'] = prods['hour'].apply(f)
print (prods)
hour session session1
0 1 Late Night Late Night
1 2 Late Night Late Night
2 3 Late Night Late Night
3 4 Late Night Late Night
4 5 Early Morning Early Morning
5 6 Early Morning Early Morning
6 7 Early Morning Early Morning
7 8 Early Morning Early Morning
8 9 Morning Morning
9 10 Morning Morning
10 11 Morning Morning
11 12 Morning Morning
12 13 Noon Noon
13 14 Noon Noon
14 15 Noon Noon
15 16 Noon Noon
16 17 Eve Eve
17 18 Eve Eve
18 19 Eve Eve
19 20 Eve Eve
20 21 Night Night
21 22 Night Night
22 23 Night Night
23 24 Night Night
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…