将持续时间创建到单独的半小时带中Pandas datetime

时间:2018-11-19 10:33:32

标签: python pandas datetime pandas-groupby timedelta

需要一点帮助。在以下工作。分隔行。

enter image description here

输入:

Name,  Channel,  Duration, Start_Time   
John, A, 2, 15:55:00    
John, A,    3, 15:57:00 
John,  A,  5, 16:00:00  
Joseph, B, 10, 15:25:00 

输出

Name, Channel,  TB, Count, Duration
John, A, 15:30:00-16:00:00,1,5
John,  A,  16:00:00-16:30:00,  1, 5
Joseph, B, 15:00:00-15:30:00, 1,    5
Joseph, B, 15:30:00-16:00:00, 1,    5

提前谢谢

1 个答案:

答案 0 :(得分:0)

使用-

df['TB'] = pd.cut(df['Start_time'], bins=pd.date_range(start='15:00:00', end='16:30:00', freq='30min'))

输出

    Name    Channel Duration    Start_Time  Start_time  TB
0   John    A   2   15:55:00    2018-11-19 15:55:00 (2018-11-19 15:30:00, 2018-11-19 16:00:00]
1   John    A   3   15:57:00    2018-11-19 15:57:00 (2018-11-19 15:30:00, 2018-11-19 16:00:00]
2   John    A   5   16:00:00    2018-11-19 16:00:00 (2018-11-19 15:30:00, 2018-11-19 16:00:00]
3   Joseph  B   10  15:25:00    2018-11-19 15:25:00 (2018-11-19 15:00:00, 2018-11-19 15:30:00]

如果您想要确切的格式,请--

df['TB'] = pd.cut(df['Start_time'], bins=pd.date_range(start='15:00:00', end='16:30:00', freq='30min')).apply(lambda x: ' - '.join(str(x).replace('(','').replace(']','').split(',')))

这将产生-

    Name    Channel Duration    Start_Time  TB
0   John    A   2   15:55:00    2018-11-19 15:30:00 - 2018-11-19 16:00:00
1   John    A   3   15:57:00    2018-11-19 15:30:00 - 2018-11-19 16:00:00
2   John    A   5   16:00:00    2018-11-19 15:30:00 - 2018-11-19 16:00:00
3   Joseph  B   10  15:25:00    2018-11-19 15:00:00 - 2018-11-19 15:30:00