3

I want to apply a similar approach of this question Select DataFrame rows between two dates but with time ranges.

I have a dataset about restaurant orders that contains time and order type. There is a time interval for breakfast, lunch and dinner.

Time intervals:

breakfast: (8:00:00 - 12:00:00) lunch: (12:00:01-16:00:00) dinner: (16:00:01-20:00:00)

Dataset sample:

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

My time column was originally type object and I converted it to timedelta64[ns].

I want to create three time ranges, one for each order_type. Then use them to validate the accuracy of my dataset.

When I have the three ranges I can run something like the below for loop:

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

I referred to the documentation and this post. To apply between_time but I kept getting errors.

leena
  • 563
  • 1
  • 8
  • 25

2 Answers2

2

You can use 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)

output:

   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
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
2

We can using pd.cut, then you just need to match the output with your original 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'])
BENY
  • 317,841
  • 20
  • 164
  • 234