【发布时间】:2022-01-15 08:08:42
【问题描述】:
您好,我想知道是否有人能够帮助解决以下问题。
在下表中,如果日期时间在 30 分钟内,我想按位置、电视和日期时间对数据进行分组,并为其分配一个组号。如果位置和电视相同,但它们的时间戳不在 30 分钟内,则应为其分配不同的组号。下面的示例表
location TV datetime
UK bake off 29/10/2021 21:20:00
UK bake off 29/10/2021 21:20:00
UK bake off 29/10/2021 21:40:00
UK masterchef 29/10/2021 22:47:00
UK masterchef 29/10/2021 23:05:00
The result I want is the below
location TV datetime group
UK bake off 29/10/2021 21:20:00 1
UK bake off 29/10/2021 21:20:00 1
UK bake off 29/10/2021 21:40:00 1
UK masterchef 29/10/2021 22:47:00 2
UK masterchef 29/10/2021 23:05:00 2
我使用 pd.Grouper 得到的结果如下。但是,由于 pd.Grouper 采用等间隔的时间间隔,因此它将第 3 行和第 5 行分组到不同的组中,如下所示。
location TV datetime group
UK bake off 29/10/2021 21:20:00 1
UK bake off 29/10/2021 21:20:00 1
UK bake off 29/10/2021 21:40:00 2
UK masterchef 29/10/2021 22:47:00 3
UK masterchef 29/10/2021 23:05:00 4
我正在使用以下代码:
df['group'] = df.groupby([pd.Grouper(key = 'datetime', freq = '30min'), 'location', 'TV']).ngroup()
【问题讨论】:
标签: python pandas time pandas-groupby