2

I have a dataframe like below:

d={
    'Date' :['2016-10-30','2016-10-30','2016-11-01','2016-10-30'],
    'Time':['09:58:11', '10:05:34', '10:07:57', '11:15:32'],
    'Transaction':[2,3,1,1]
}

df=pd.DataFrame(d, columns=['Date','Time','Transaction'])

enter image description here

I need to create a new variable as Time_Group. For (6,11] is 'Morning' ,for (11,17] is 'Afternoon' and for (17,20] is 'Evening' for data of Time_group. How to sub create this variable by using Time column?

2 Answers 2

4

Using pd.cut with pd.Timedelta:

u = df.assign(Time=pd.to_timedelta(df['Time']))
bins = [6,11,17,20]
labels = ['Morning','Afternoon','Evening']
u = u.assign(Time_Group=pd.cut(u['Time'],[pd.Timedelta(hours=i) for i in bins],
                               labels=labels))

print(u)
         Date     Time  Transaction Time_Group
0  2016-10-30 09:58:11            2    Morning
1  2016-10-30 10:05:34            3    Morning
2  2016-11-01 10:07:57            1    Morning
3  2016-10-30 11:15:32            1  Afternoon
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, here 4th raw should be Morning but, it looks Afternoon. How to fix this?
@user14815110 in your question you have written that 11-17 should be afternoon. Hence the 4th row is afternoon since it is 15 min past 11.to change the timing you can simply change the bins list from 11 to 12 for example to start the afternoon from
1

You can use this -

d={
    'Date' :['2016-10-30','2016-10-30','2016-11-01','2016-10-30'],
    'Time':['09:58:11', '10:05:34', '10:07:57', '11:15:32'],
    'Transaction':[2,3,1,1]
}

df=pd.DataFrame(d, columns=['Date','Time','Transaction'])


def time_group(inp):
    inp = datetime.datetime.strptime(inp[0], "%H:%M:%S")
    a = datetime.datetime.strptime("06:00:00", "%H:%M:%S")
    b = datetime.datetime.strptime("11:00:00", "%H:%M:%S")
    c = datetime.datetime.strptime("17:00:00", "%H:%M:%S")
    d = datetime.datetime.strptime("20:00:00", "%H:%M:%S")
    
    if a < inp <= b:
       return 'Morning'
    elif b < inp < c:
       return 'Afternoon'
    elif c < inp < d:
       return 'Night'

>>> df[['Time']].apply(time_group,axis=1)
0      Morning
1      Morning
2      Morning
3    Afternoon
dtype: object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.