Resample a request log to hourly traffic, filling empty hours with zeros

HardpandasPro

Capacity planning for an LLM endpoint needs traffic per hour, and quiet hours matter as much as busy ones. Grouping by hour skips hours with no requests, which breaks charts and averages.

Write hourly_traffic(df) where df has columns ts ('YYYY-MM-DD HH:MM' string) and tokens (int), rows in arbitrary order.

Return a DataFrame with columns exactly [hour, requests, tokens, tokens_per_request], one row for EVERY hour from the hour of the earliest request to the hour of the latest, inclusive, sorted by hour, plain 0..n-1 index.
- hour: the hour start as a 'YYYY-MM-DD HH:00' string.
- requests: number of rows in that hour; tokens: their token sum (both 0 for empty hours).
- tokens_per_request: tokens / requests as a float, 0.0 when requests is 0.

Signaturedef hourly_traffic(df)

Example

requests at 10:05 (100 tokens), 10:40 (50) and 12:10 (30) give hours 10:00, 11:00, 12:00 with requests 2, 0, 1, tokens 150, 0, 30 and tokens_per_request 75.0, 0.0, 30.0.

Understand the idea

For capacity planning you need traffic for every hour, including quiet ones. Grouping by hour only creates rows for hours that had requests, so empty hours vanish and charts and averages go wrong. Resampling builds a regular hourly grid from the first hour to the last and fills empty hours with zero counts and zero sums. Worked example: requests at 09:15 (40 tokens), 09:50 (20) and 11:30 (60). Hours: 09:00, 10:00, 11:00. requests = [2, 0, 1], tokens = [60, 0, 60]. tokens_per_request = [30.0, 0.0, 60.0], where the empty hour gives 0.0 instead of a division by zero. Rule: parse ts as datetimes and use them as the index; resample to 1 hour, counting rows and summing tokens; tokens_per_request = tokens / requests where requests > 0, else 0.0; format hour as 'YYYY-MM-DD HH:00'; output columns exactly [hour, requests, tokens, tokens_per_request], sorted, plain 0 to n-1 index. Input rows may be in any order, so sort first. Used when sizing GPU capacity for an LLM endpoint.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplehourly_traffic(_d1()).to_dict('list')
  • Sample 2: across midnight with gapshourly_traffic(_d2()).to_dict('list')