Pandas · Calculate rolling metrics
Google Search Analytics
Course overviewGoogle Search · Analyze activity over time

Calculate rolling metrics

Choose a trailing window and minimum coverage explicitly.

Step 1 of 3 · Learn

Choose how much history is required

.rolling(7, min_periods=1).mean() averages up to seven rows, including the current row. With min_periods=7, the first six results stay missing. Keep zero-count days: removing them changes the window and its denominator.

indexsearches
02
10
24
36
indexsearchespartialcomplete
022NA
101NA
2422
363.333333.33333
The same window gives early averages only when partial coverage is allowed.

Rows and elapsed time are different

.rolling("7D", closed="right") needs a sorted datetime index and covers (current time minus seven days, current time]. The left endpoint is excluded. Seven daily midnight rows and a complete calendar make this the current day plus the six preceding dates. On irregular data, seven rows need not be seven days.

indexdatevalue
02026-07-0610
12026-07-0720
22026-07-1030
indexdatemean
02026-07-06 00:00:00+00:0010
12026-07-07 00:00:00+00:0015
22026-07-10 00:00:00+00:0030
A three-day window at July 10 excludes July 7; three rows would include it.

Make the metric and coverage explicit

Use .sum() for a trailing count and .mean() for its daily average. Set min_periods explicitly for both row-based and time-based windows; their defaults differ. Keep center=False, the default, so future rows never contribute.

▷ Your turn

From daily_searches, return date, searches, and trailing_mean sorted by date ascending. Average the current date and up to six preceding calendar dates, using available report dates from the start. Include zero-count days, do not round, and preserve UTC timestamps. Save the DataFrame as result.

daily_searches contains date and searches for every UTC date from July 6 through August 30, 2026, with 0 on dates without searches. It is built from searches inside that interval; earlier dates are not available for the first comparison or rolling window.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.