liveBook · Manning

Window function

As explained in The Well-Grounded Data Analyst

A window function is a SQL operation that computes a result over related rows while retaining each row in the query result.

A window function computes a value across related rows while keeping each row available for further analysis. It is useful when hourly values must be compared with each location’s daily total rather than collapsed into a separate summary table. section 9.2.1

In SQL, partition rows with PARTITION BY to place the hourly and daily measures side by side. A separate aggregation followed by a join is also valid, but a window-like calculation appends the group total directly to the detailed data. section 9.2.1

Hourly share of daily cycling traffic

First aggregate cycling counts to one row per location, date, and hour. Then group by location and date, use pandas transform('sum') to add TotalDailyCount to every hourly row, and divide Pedal_cycles by that total to calculate hourly_pct. Check the resulting daily counts and percentages before plotting their distribution by hour. section 9.2.1

cycling_daily_hourly['TotalDailyCount'] = (
    cycling_daily_hourly
    .groupby(['Count_point_id', 'Count_date'])
    ['Pedal_cycles']
    .transform('sum')     #1
)

cycling_daily_hourly['hourly_pct'] = (
    cycling_daily_hourly['Pedal_cycles']
    / cycling_daily_hourly['TotalDailyCount']
)

cycling_daily_hourly

Inspect the transform-based calculation that preserves hourly rows while adding each location-date daily total. section 9.2.1

How The Well-Grounded Data Analyst covers it

How deep it goes
Demonstrates a practical pandas transform workflow and verification step, without detailing SQL window-function syntax beyond PARTITION BY.
Examples
Uses hourly bicycle counts by location and date to compute each hour’s percentage of daily cycling traffic.
What it assumes
Assumes familiarity with SQL or pandas grouping and aggregation operations.
What you can do after
Apply it via pandas transform to append group totals and calculate row-level percentages.
How it connects
Connects window functions with SQL PARTITION BY, pandas transform, groupby aggregation, joins, and box plots.

Also explained in

Compare how 3 books explain window function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Data Analyst. The section links point to the parts of the book it draws on.