Python 从数据帧中的Datetime列获取时隙

Python 从数据帧中的Datetime列获取时隙,python,pandas,dataframe,Python,Pandas,Dataframe,我有这样一个数据框: Datetime Transaction Item 3/16/2020 9:58 1 X 3/17/2020 10:05 2 Y 3/18/2016 14:48 3 Z 我需要的是将Datetime列转换为工作日和一小时的时隙?例如: Weekday TimeSlot

我有这样一个数据框:

Datetime            Transaction        Item
3/16/2020 9:58        1                 X
3/17/2020 10:05       2                 Y
3/18/2016 14:48       3                 Z
我需要的是将Datetime列转换为工作日和一小时的时隙?例如:

Weekday              TimeSlot        Transaction        Item
1                      9-10              1              X
2                     10-11             2              Y
3                     14-15             3              Z
我尝试了以下方法,但没有成功:

df['Weekday'] = df['Datetime'].dt.dayofweek
df['Hour'] = df['Datetime'].dt.hour
df.Datetime = pd.to_datetime(df.Datetime)
df['slot'] = df.groupby(df.Datetime.dt.hour//1).ngroup()+1

有简单的方法吗?我正在使用Python-3。

我不确定工作日在这里做什么。这不就是把时间提取出来,加上一个小时吗

hours = df['Datetime'].dt.hour

df['TimeSlot'] = hours.astype(str) + "-" + hours.add(1).astype(str)
输出:

             Datetime  Transaction Item TimeSlot
0 2016-10-30 09:58:00            1    X     9-10
1 2016-10-30 10:05:00            2    Y    10-11
2 2016-10-30 14:48:00            3    Z    14-15

在将
Datetime
列转换为真正的时间戳类型后,工作日没有问题:

dt = pd.to_datetime(df['Datetime'])
df['Weekday'] = dt.dt.dayofweek
该时段为
\u小时\u-\u小时+1小时
,除非您即将更改日期,该时段变为
23-0

你可以做:

start_hour = dt.dt.hour
end_hour = pd.Series(np.where(start_hour == 23, 0, start_hour +1),
                     index=start_hour.index)
df['Slot'] = start_hour.astype(str) + '-' + end_hour.astype(str)