将时间转换为分类变量[重复]
Posted
技术标签:
【中文标题】将时间转换为分类变量[重复]【英文标题】:Convert time to categorical variable [duplicate] 【发布时间】:2020-12-11 08:29:09 【问题描述】:df
Time | Day_of_the_Week
16:24:18 | Sat
17:00:01 | Sun
03:48:12 | Mon
预期输出:
df
Time | Day_of_the_Week | Time_Category
16:24:18 | Sat | Afternoon
17:00:01 | Sun | Evening
03:48:12 | Mon | Midnight
df['Time'][1] 返回一个“datetime.time”
以下代码返回无效语法。
for a in df:
if df['Time'] > 17:00:00:
df['Time_Category'] == 'Evening'
elif df['Time'] > '12:00:00':
df['Time_Category'] == 'Afternoon'
elif df['Time'] > '04:00:00':
df['Time_Category'] == 'Morning'
else:
df['Time_Category'] == 'Midnight'
【问题讨论】:
【参考方案1】:我们可以试试pd.cut
s = pd.cut(df.Time, pd.to_timedelta(['04:00:00','12:00:00','17:00:00','23:59:59']),
labels=['Morning','Afternoon','Evening']).astype(str).replace('nan','Midnight')
Out[43]:
0 Afternoon
1 Evening
2 Midnight
Name: Time, dtype: object
df['Time_category'] = s
【讨论】:
我得到一个 'TypeError: ' @Luc df.Time=pd.to_timedelta(df.Time)以上是关于将时间转换为分类变量[重复]的主要内容,如果未能解决你的问题,请参考以下文章