最近n天的滚动计数

时间:2020-05-18 17:35:45

标签: pandas rolling-computation

我有以下数据框:

entry_time_flat           route_id      time_slot          

2019-09-02 00:00:00           1_2            0-6
2019-09-04 00:00:00           3_4            6-12
2019-09-06 00:00:00           1_2            0-6
2019-09-06 00:00:00           1_2           18-20
...

我想为每个route_id和time_slot创建一个final_df,以计算最近n天(n_days = 30)中出现的次数。

为了说明,我想获得以下df:

print(final_df)

entry_time_flat           route_id      time_slot    n_occurrences        

2019-09-02 00:00:00           1            0-6             0
2019-09-04 00:00:00           3            6-12            0
2019-09-06 00:00:00           1            0-6             1
2019-09-06 00:00:00           1            18-20           0
...

我如何才能有效地获得该结果?

1 个答案:

答案 0 :(得分:1)

您可以将pd.DataFrame.rolling与偏移量一起使用:

# set date column as index, make sure it is sorted
df.set_index('entry_time_flat',inplace=True)
df.sort_index(inplace=True)

# define offset
n_days = 30
offset = str(n_days)+'D'

# count
final_df = df.groupby(['route_id','time_slot'])['route_id'].rolling(offset,closed='left').count()
final_df.fillna(0,inplace=True)

# get desired output format
final_df.name = 'n_occurrences'
final_df = final_df.reset_index()

编辑:看起来您希望间隔是左封闭的。相应地更改了答案。