python - 在 Pandas 中创建时间范围

标签 python pandas datetime time

我想对这个问题应用类似的方法 Select DataFrame rows between two dates 但有时间范围。

我有一个关于餐厅订单的数据集,其中包含时间和订单类型。早餐、午餐和晚餐是有时间间隔的。

时间间隔:

breakfast: (8:00:00 - 12:00:00) lunch: (12:00:01-16:00:00) dinner: (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 列最初是 object 类型,我将其转换为 timedelta64[ns]

我想创建三个时间范围,每个时间范围对应一个 order_type。然后使用它们来验证我的数据集的准确性。

当我有三个范围时,我可以运行类似下面的 for 循环:

for order in dirtyData['order_type']:
    for time in dirtyData['time']:
        if order=='Breakfast' and time not in BreakfastRange:
            *do something*

我提到了 documentation还有这个post .应用 between_time 但我一直收到错误。

最佳答案

你可以使用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

关于python - 在 Pandas 中创建时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177231/

相关文章:

Python字典键(类对象)与多个比较器的比较

c# - 在托管代码中,如何实现良好的引用位置?

python - 从 Pandas 中的过滤结果创建 bool 掩码

python - Pandas dataframe to_datetime() 转换日期不正确

mysql - 查询特定日期时间的数据库(没有秒或毫秒)

Python 作用域/静态误解

python - 如何转换为多线程子进程

python - 在 pandas 数据框(和)列表上使用 scipy pdist

带时区的 PostgreSQL date()

python - 如何将 pandas 中的 timedelta 列转换为字符串