【问题标题】:Create Time Ranges in Pandas在 Pandas 中创建时间范围
【发布时间】:2020-01-30 07:11:26
【问题描述】:

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

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

时间间隔:

早餐:(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 列最初的类型是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*

我提到了documentation 和这个post。申请between_time,但我不断收到错误。

【问题讨论】:

    标签: python pandas datetime time


    【解决方案1】:

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

    【讨论】:

    • 很好,7 秒
    • 对不起,我不明白你的解决方案。什么是ranges,什么是bins
    【解决方案2】:

    我们可以使用pd.cut,那么你只需要将输出与你原来的order_type相匹配

    pd.cut(df.time,pd.to_timedelta(['00:00:00','12:00:00','16:00:00','23:59:59']),labels=['B','L','D'])
    

    【讨论】:

    • 完美运行,谢谢。我对代码的简单程度感到惊讶。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2019-05-22
    相关资源
    最近更新 更多