Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

python - Calculating a rolling window of 8 hour size, using half hour increments in pandas

I have a data frame with the following date column:

scheduled_departure_utc run_id
0 2021-01-11 13:07:00+00:00 13149
128 2021-01-11 13:07:00+00:00 38138
1 2021-01-11 13:37:00+00:00 13153
129 2021-01-11 13:37:00+00:00 38139
2 2021-01-11 18:07:00+00:00 951600
130 2021-01-11 18:07:00+00:00 951600
3 2021-01-11 18:22:00+00:00 951780
131 2021-01-11 18:22:00+00:00 951780
132 2021-01-11 18:26:00+00:00 951201
4 2021-01-11 18:37:00+00:00 951802

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way would be to first resample the dataframe to have the same frequency as your wanted step-size (in this case 30 minutes). Then you can use rolling with a window size of 16 (i.e., 8 hours).

df['scheduled_departure_utc'] = pd.to_datetime(df['scheduled_departure_utc'])
df.set_index('scheduled_departure_utc').resample('30T').count()['run_id'].rolling(window=16, min_periods=1).sum()

Resulting pandas series:

2021-01-11 13:00:00     2.0
2021-01-11 13:30:00     4.0
2021-01-11 14:00:00     4.0
2021-01-11 14:30:00     4.0
2021-01-11 15:00:00     4.0
2021-01-11 15:30:00     4.0
2021-01-11 16:00:00     4.0
2021-01-11 16:30:00     4.0
2021-01-11 17:00:00     4.0
2021-01-11 17:30:00     4.0
2021-01-11 18:00:00     9.0
2021-01-11 18:30:00    10.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...