python - 在 Pandas 中创建时间范围
问题描述
我想对这个问题应用类似的方法Select DataFrame rows between two dates but with time range 。
我有一个关于餐厅订单的数据集,其中包含时间和订单类型。早餐、午餐和晚餐有一个时间间隔。
时间间隔:
早餐:(8:00:00-12:00:00) 午餐:(12:00:01-16:00:00) 晚餐:(16:00:01-20:00:00)
数据集样本:
order_type time
0 Lunch 13:24:30
1 Dinner 18:28:43
2 Dinner 17:17:44
3 Lunch 15:46:28
4 Lunch 12:33:48
5 Lunch 15:26:11
6 Lunch 13:04:13
7 Lunch 12:13:31
8 Breakfast 08:20:16
9 Breakfast 08:10:08
10 Dinner 18:08:27
11 Breakfast 10:42:15
12 Dinner 19:09:17
13 Dinner 18:28:43
14 Breakfast 09:21:07
我的time
专栏最初是 type object
,我将其转换为timedelta64[ns]
.
我想创建三个时间范围,每个时间范围一个order_type
。然后使用它们来验证我的数据集的准确性。
当我拥有三个范围时,我可以运行如下内容for loop
:
for order in dirtyData['order_type']:
for time in dirtyData['time']:
if order=='Breakfast' and time not in BreakfastRange:
*do something*
解决方案
您可以使用pd.cut
:
# threshold for time range
bins = pd.to_timedelta(['8:00:00', '12:00:00', '16:00:00', '20:00:00'])
# cut:
df['order_type_gt'] = pd.cut(df['time'],
bins,
labels=['Breakfast','Lunch', 'Dinner'],
include_lowest=True)
输出:
order_type time order_type_gt
0 Lunch 13:24:30 Lunch
1 Dinner 18:28:43 Dinner
2 Dinner 17:17:44 Dinner
3 Lunch 15:46:28 Lunch
4 Lunch 12:33:48 Lunch
5 Lunch 15:26:11 Lunch
6 Lunch 13:04:13 Lunch
7 Lunch 12:13:31 Lunch
8 Breakfast 08:20:16 Breakfast
推荐阅读
- latex - 如何在图片中插入特殊符号
- node.js - Heroku 不允许临时下载。我该如何解决这个限制?
- .htaccess - 如何在 app.yaml 中正确路由目录调用?
- c# - 在单个剃须刀视图中,我如何检索从控制器的不同方法传递的值?
- http2 - http2 客户端无法解析 HTTP 升级响应标头
- sql - 如果每个对象/项目有超过一个数字 (4),则删除关系
- c++ - 不确定我在寻找什么(矩阵,类似 db 的结构)来按标签组织文件
- python - 尝试在函数外循环追加列表
- django - Django:删除 db.sql3 文件/新数据库时,无法创建用户:save() 得到了意外的关键字参数“force_insert”
- ruby-on-rails - Rails 5 API - has_many 通过创建操作返回 2 条记录,尽管只有 1 条记录保存在数据库中