gpt4 book ai didi

python - 如何在Python中分割时间数据?

转载 作者:行者123 更新时间:2023-12-02 19:00:47 26 4
gpt4 key购买 nike

我有一个如下所示的数据框:

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

我需要创建一个新变量作为 Time_Group。对于 Time_group 的数据,For (6,11] 为“上午”,for (11,17] 为“下午”,for (17,20] 为“晚上”。如何使用时间列子创建此变量?

最佳答案

pd.cutpd.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

关于python - 如何在Python中分割时间数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65600964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com