'Fill dataframe with consecutive datetimes

I have a DataFrame:

|         init      |          end        | temp
2022-02-02 10:34:00 | 2022-02-02 11:34:00 | 34
2022-02-02 11:34:00 | 2022-02-02 12:34:00 | 12
2022-02-02 13:34:00 | 2022-02-02 14:34:00 | 23
2022-02-02 14:34:00 | 2022-02-02 15:34:00 | 22
2022-02-02 17:34:00 | 2022-02-02 18:34:00 | 18

I need to fill in the missing times (the end of one is the beginning of another) from a start and end date, if I have start=2022-02-02 09:34:00 end=2022-02-02 18:34:00 I need to fill the DataFrame as follows:

|         init      |          end        | temp
**2022-02-02 09:34:00 | 2022-02-02 11:34:00 | 0**
2022-02-02 10:34:00 | 2022-02-02 11:34:00 | 34
2022-02-02 11:34:00 | 2022-02-02 12:34:00 | 12
**2022-02-02 12:34:00 | 2022-02-02 11:34:00 | 0**
2022-02-02 13:34:00 | 2022-02-02 14:34:00 | 23
2022-02-02 14:34:00 | 2022-02-02 15:34:00 | 22
**2022-02-02 15:34:00 | 2022-02-02 11:34:00 | 0**
**2022-02-02 16:34:00 | 2022-02-02 11:34:00 | 0**
2022-02-02 17:34:00 | 2022-02-02 18:34:00 | 18
**2022-02-02 18:34:00 | 2022-02-02 11:34:00 | 0**


Solution 1:[1]

You can use a combination of pd.date_range and pd.Timedelta:

import pandas as pd

# Create the sample dataframe
df = pd.DataFrame({'init': ['2022-02-02 10:34:00', '2022-02-02 11:34:00', '2022-02-02 13:34:00', '2022-02-02 14:34:00', '2022-02-02 17:34:00'], 'end': ['2022-02-02 11:34:00', '2022-02-02 12:34:00', '2022-02-02 14:34:00', '2022-02-02 15:34:00', '2022-02-02 18:34:00'], 'temp': [34, 12, 23, 22, 18]})

# Convert init and end columns into a datetime type
df['init'] = pd.to_datetime(df['init'])
df['end'] = pd.to_datetime(df['end'])

# Fill the missing values
start, end ='2022-02-02 09:34:00', '2022-02-02 18:34:00'
hr = pd.date_range(start, end, freq='H')
df_hr = pd.DataFrame(zip(hr, hr + pd.Timedelta(hours=1)), columns=['init', 'end'])
df = df_hr.merge(df, how='left', on=['init', 'end']).fillna(0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1