Python/Pandas基于DateTime值创建分类列
我有一个带有列['date']的pandas dataframe(数据),其值是“ yyyy-mm-dd hh:mm:ss”,我将我转换为pandas dateTime格式。
data ['date'] = pd.to_datetime(data ['date'])
如何使用类别'早期','mid--创建一个新的分类列['time']一天,“迟到”,根据每天的时间?
我尝试了以下错误:
def time(x):
if '03:00:00' < x <= '11:00:00':
return 'Early'
elif '11:00:00' < x <= '17:00:00':
return 'Mid-day'
return 'Late'
data['Time'] = data['Date'].dt.time.apply(time)
但是我得到了这个错误:“ TypeError:'&lt;'在“ str”和“ dateTime”实例之间不支持“时间”。“
感谢您的帮助!
I have a Pandas Dataframe (data) with a column ['Date'] with values like "yyyy-mm-dd HH:MM:SS" that I converted into Pandas Datetime format.
data['Date'] = pd.to_datetime(data['Date'])
How can I create a new categorical column ['Time'] with categories 'Early', 'Mid-day', 'Late' based on the hour of each day?
I tried this:
def time(x):
if '03:00:00' < x <= '11:00:00':
return 'Early'
elif '11:00:00' < x <= '17:00:00':
return 'Mid-day'
return 'Late'
data['Time'] = data['Date'].dt.time.apply(time)
But I get this error: " TypeError: '<' not supported between instances of 'str' and 'datetime.time' "
I would appreciate your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
pandas.cut.cut.cut
。但是,这有点棘手,因为您需要先将日期时间转换为TimeDelta:输出:
You can use
pandas.cut
. It is however a bit tricky as you need to convert first your datetime to timedelta:output:
如何将所有条件包装在to_dateTime()中?
How about just wrapping all of your conditions in your function in a to_datetime() ?
您可以将
np.select
与dateTimeIndex.indexer_between_time
功能一起创建标签。indexer_between_time
返回所提供端点之间的时间的数组索引,因此您需要从 in 使用dataframe的阵列中核对 in 检查。You can use
np.select
together with theDatetimeIndex.indexer_between_time
functionality to create the labels.indexer_between_time
returns the array indices where the time is between the provided endpoints, so you need to form the Boolean series from anin
check with an array the length of the DataFrame.