Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

pandas - How to split time data in Python?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...