How to split time data in Python?

Viewed 191

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

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

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
Related