Dividing Time Intervals With Multiple Index Into Hourly Buckets In Python
here is the code for the sample data set I have data={'ID':[4,4,4,4,22,22,23,25,29], 'Zone':[32,34,21,34,27,29,32,75,9], 'checkin_datetime':['04-01-2019 13:07','04-01-2019
Solution 1:
Not sure if this is efficient, but should work.
import pandas as pd
from datetime import timedelta
def group_into_hourly_buckets(df):
df['duration'] = df['checkout_datetime'] - df['checkin_datetime']
grouped_data = []
for idx, row in df.iterrows():
dur = row['duration'].seconds//60
start_time = row['checkin_datetime']
hours_ = 0
while dur > 0:
_data = {}
_data['Checked_in_hour'] = start_time.floor('H') + timedelta(hours=hours_)
time_spent_in_window = min(dur, 60)
if (hours_ == 0):
time_spent_in_window = min(time_spent_in_window, ((start_time.ceil('H') - start_time).seconds)//60)
_data['checked_in_minutes'] = time_spent_in_window
_data['ID'] = row['ID']
_data['Zone'] = row['Zone']
dur -= time_spent_in_window
hours_ += 1
grouped_data.append(_data)
return pd.DataFrame(grouped_data)
Post a Comment for "Dividing Time Intervals With Multiple Index Into Hourly Buckets In Python"