I have a dataframe with 2 timestamp columns ('start' and 'end'). I want to explode the rows of the dataframe such that I can split the timestamp by hours.
Here is an example:
import pandas as pd
df = pd.DataFrame({'id_kanban': [244],'component': ['A'],'start': ['2021-02-02 11:03:18'], 'end': ['2021-02-02 13:33:28']})
print(df)
The output I´m getting is:
df1 = pd.DataFrame({
'id_kanban': [244, 244, 244, 244],
'component': ['A', 'A', 'A', 'A'],
'start': ['2021-02-02 11:03:18', '2021-02-02 01:00:00',
'2021-02-02 01:00:00', '2021-02-02 01:00:00'],
'end': ['2021-02-02 01:00:00', '2021-02-02 01:00:00',
'2021-02-02 01:00:00','2021-02-02 13:33:28']})
However, the output I want to get is:
df2 = pd.DataFrame({
'id_kanban': [244, 244, 244],
'component': ['A', 'A', 'A'],
'start': ['2021-02-02 11:03:18', '2021-02-02 12:00:00',
'2021-02-02 13:00:00'],
'end': ['2021-02-02 12:00:00', '2021-02-02 13:00:00',
'2021-02-02 13:33:28']})
The code I'm using is similar to the one found in a similar question: How can I split the difference between two timestamps that contain more than one month in a Pandas DataFrame
This is the code I´m trying:
def find_interval(sr):
dti = pd.date_range(sr['start'], sr['end'], freq='H').normalize() \
+ pd.Timedelta(hours=1)
return list(zip([sr['start']] + dti.tolist(), dti.tolist() + [sr['end']]))
df1 = df.apply(find_interval, axis=1).explode().apply(pd.Series)
df1 = df.drop(columns=['start', 'end']) \
.join(df1).rename(columns={0: 'start', 1: 'end'})
Any ideas on how to output the correct dataframe? Thanks