Reshaping and Tidy Data
There's a whole paper by Hadley Wickham about tidy data but it's in a PDF so you're probably not going to read it. Here's the paper's definition of tidy data:
- Each variable forms a column.
- Each observation forms a row.
- Each type of observational unit forms a table.
As Dr Wickham notes, this is Codd's 3rd Normal Form but in statspeak rather than databasespeak.
The meaning of "variable" and "observation" depend on what we're studying, so tidy data is a concept that you mostly learn through experience and β¨vibesβ¨.
Now we'll explore what tidy data looks like for an NBA results dataset.
Get the data
import nanuq
let nbaGlob = "data/modern-polars/nba/*.csv"
nbShow scanCsv(nbaGlob).head.collect
| date | away_team | away_points | home_team | home_points |
|---|---|---|---|---|
| str | str | i64 | str | i64 |
| "Fri, Apr 1, 2016" | "Philadelphia 76ers" | 91 | "Charlotte Hornets" | 100 |
| "Fri, Apr 1, 2016" | "Dallas Mavericks" | 98 | "Detroit Pistons" | 89 |
| "Fri, Apr 1, 2016" | "Brooklyn Nets" | 91 | "New York Knicks" | 105 |
| "Fri, Apr 1, 2016" | "Cleveland Cavaliers" | 110 | "Atlanta Hawks" | 108 |
| "Fri, Apr 1, 2016" | "Toronto Raptors" | 99 | "Memphis Grizzlies" | 95 |
import polars as pl
nba_glob = "data/modern-polars/nba/*.csv"
pl.scan_csv(nba_glob).head().collect()| date | away_team | away_points | home_team | home_points |
|---|---|---|---|---|
| str | str | i64 | str | i64 |
| "Fri, Apr 1, 2016" | "Philadelphia 76ers" | 91 | "Charlotte Hornets" | 100 |
| "Fri, Apr 1, 2016" | "Dallas Mavericks" | 98 | "Detroit Pistons" | 89 |
| "Fri, Apr 1, 2016" | "Brooklyn Nets" | 91 | "New York Knicks" | 105 |
| "Fri, Apr 1, 2016" | "Cleveland Cavaliers" | 110 | "Atlanta Hawks" | 108 |
| "Fri, Apr 1, 2016" | "Toronto Raptors" | 99 | "Memphis Grizzlies" | 95 |
Cleaning π§Ή
Nothing super interesting here:
let gamesPl = scanCsv(nbaGlob)
.withColumns(
col.date.str.strptime(Date, "%a, %b %d, %Y"))
.sort("date")
.withRowIndex("game_id")
nbShow gamesPl.head.collect
| game_id | date | away_team | away_points | home_team | home_points |
|---|---|---|---|---|---|
| u32 | date | str | i64 | str | i64 |
| 0 | 2015-10-27 | "Cleveland Cavaliers" | 95 | "Chicago Bulls" | 97 |
| 1 | 2015-10-27 | "Detroit Pistons" | 106 | "Atlanta Hawks" | 94 |
| 2 | 2015-10-27 | "New Orleans Pelicans" | 95 | "Golden State Warriors" | 111 |
| 3 | 2015-10-28 | "Washington Wizards" | 88 | "Orlando Magic" | 87 |
| 4 | 2015-10-28 | "Philadelphia 76ers" | 95 | "Boston Celtics" | 112 |
games_pl = (
pl.scan_csv(nba_glob)
.with_columns(
pl.col("date").str.strptime(pl.Date, "%a, %b %d, %Y"),
)
.sort("date")
.with_row_index("game_id")
)
games_pl.head().collect()| game_id | date | away_team | away_points | home_team | home_points |
|---|---|---|---|---|---|
| u32 | date | str | i64 | str | i64 |
| 0 | 2015-10-27 | "Cleveland Cavaliers" | 95 | "Chicago Bulls" | 97 |
| 1 | 2015-10-27 | "Detroit Pistons" | 106 | "Atlanta Hawks" | 94 |
| 2 | 2015-10-27 | "New Orleans Pelicans" | 95 | "Golden State Warriors" | 111 |
| 3 | 2015-10-28 | "Washington Wizards" | 88 | "Orlando Magic" | 87 |
| 4 | 2015-10-28 | "Philadelphia 76ers" | 95 | "Boston Celtics" | 112 |
Polars does have a
drop_nulls
method but the only parameter it takes is subset, which lets you consider null values just for
a subset of the columns. Polars drop_nulls will drop the row if any values are null. If you
only want to drop when all values are null, the docs recommend
.filter(~pl.all_horizontal(pl.all().is_null())).
A previous version of the Polars example used
pl.fold, which is for fast horizontal
operations. It doesn't come up anywhere else in this book, so consider this your warning that it
exists.
Pivot and Melt
Here's a simple explanation of pivoting and melting. If you already know what pivot and
melt are, feel free to scroll past this bit.
Pivot
Suppose you have a dataframe that looks like this:
import std/sequtils
let prices = newDataFrame(
series("date", sequtils.repeat(date(2020, 1, 1), 4) & sequtils.repeat(date(2020, 1, 2), 4) &
sequtils.repeat(date(2020, 1, 3), 4)),
series("ticker", cycle(["AAPL", "TSLA", "MSFT", "NFLX"], 3)),
series("price", [100, 200, 300, 400, 110, 220, 330, 420, 105, 210, 315, 440]))
nbShow prices
| date | ticker | price |
|---|---|---|
| date | str | i64 |
| 2020-01-01 | "AAPL" | 100 |
| 2020-01-01 | "TSLA" | 200 |
| 2020-01-01 | "MSFT" | 300 |
| 2020-01-01 | "NFLX" | 400 |
| 2020-01-02 | "AAPL" | 110 |
| … | … | … |
| 2020-01-02 | "NFLX" | 420 |
| 2020-01-03 | "AAPL" | 105 |
| 2020-01-03 | "TSLA" | 210 |
| 2020-01-03 | "MSFT" | 315 |
| 2020-01-03 | "NFLX" | 440 |
from datetime import date
prices = pl.DataFrame({
"date": [*[date(2020, 1, 1)]*4, *[date(2020, 1, 2)]*4, *[date(2020, 1, 3)]*4],
"ticker": [*["AAPL", "TSLA", "MSFT", "NFLX"]*3],
"price": [100, 200, 300, 400, 110, 220, 330, 420, 105, 210, 315, 440],
})
prices| date | ticker | price |
|---|---|---|
| date | str | i64 |
| 2020-01-01 | "AAPL" | 100 |
| 2020-01-01 | "TSLA" | 200 |
| 2020-01-01 | "MSFT" | 300 |
| 2020-01-01 | "NFLX" | 400 |
| 2020-01-02 | "AAPL" | 110 |
| … | … | … |
| 2020-01-02 | "NFLX" | 420 |
| 2020-01-03 | "AAPL" | 105 |
| 2020-01-03 | "TSLA" | 210 |
| 2020-01-03 | "MSFT" | 315 |
| 2020-01-03 | "NFLX" | 440 |
You can call df.pivot to get a dataframe that looks like this:
let pivoted = prices.pivot(index = "date", values = "price", on = "ticker")
nbShow pivoted
| date | AAPL | TSLA | MSFT | NFLX |
|---|---|---|---|---|
| date | i64 | i64 | i64 | i64 |
| 2020-01-01 | 100 | 200 | 300 | 400 |
| 2020-01-02 | 110 | 220 | 330 | 420 |
| 2020-01-03 | 105 | 210 | 315 | 440 |
pivoted = prices.pivot(index="date", values="price", on="ticker")
pivoted| date | AAPL | TSLA | MSFT | NFLX |
|---|---|---|---|---|
| date | i64 | i64 | i64 | i64 |
| 2020-01-01 | 100 | 200 | 300 | 400 |
| 2020-01-02 | 110 | 220 | 330 | 420 |
| 2020-01-03 | 105 | 210 | 315 | 440 |
As you can see, .pivot creates a dataframe where the columns are the unique labels from one
column ("ticker"), alongside the index column ("date"). The values for the non-index columns are
taken from the corresponding rows of the values column ("price").
If our dataframe had multiple prices for the same ticker on the same date, we would use the
aggregate_function parameter of the .pivot method, e.g.:
prices.pivot(..., aggregate_function="mean"). Pivoting with an aggregate function gives us
similar behaviour to what Excel calls "pivot tables".
Melt / Unpivot
Melt is the inverse of pivot. While pivot takes us from long data to wide data, melt goes from wide to long.
Note: Polars has recently replaced its melt method with an unpivot method.
If we call .unpivot(index="date", value_name="price") on our pivoted dataframe we get our
original dataframe back:
nbShow pivoted.unpivot(index = "date", valueName = "price")
| date | variable | price |
|---|---|---|
| date | str | i64 |
| 2020-01-01 | "AAPL" | 100 |
| 2020-01-02 | "AAPL" | 110 |
| 2020-01-03 | "AAPL" | 105 |
| 2020-01-01 | "TSLA" | 200 |
| 2020-01-02 | "TSLA" | 220 |
| … | … | … |
| 2020-01-02 | "MSFT" | 330 |
| 2020-01-03 | "MSFT" | 315 |
| 2020-01-01 | "NFLX" | 400 |
| 2020-01-02 | "NFLX" | 420 |
| 2020-01-03 | "NFLX" | 440 |
pivoted.unpivot(index="date", value_name="price")| date | variable | price |
|---|---|---|
| date | str | i64 |
| 2020-01-01 | "AAPL" | 100 |
| 2020-01-02 | "AAPL" | 110 |
| 2020-01-03 | "AAPL" | 105 |
| 2020-01-01 | "TSLA" | 200 |
| 2020-01-02 | "TSLA" | 220 |
| … | … | … |
| 2020-01-02 | "MSFT" | 330 |
| 2020-01-03 | "MSFT" | 315 |
| 2020-01-01 | "NFLX" | 400 |
| 2020-01-02 | "NFLX" | 420 |
| 2020-01-03 | "NFLX" | 440 |
Tidy NBA data
Suppose we want to calculate the days of rest each team had before each game. In the current
structure this is difficult because we need to track both the home_team and away_team
columns. We'll use .unpivot so that there's a single team column. This makes it easier to
add a rest column with the per-team rest days between games.
let tidyPl = gamesPl
.unpivot(
index = ["game_id", "date"],
on = ["away_team", "home_team"],
valueName = "team")
.sort("game_id")
.withColumns((
col.date
.alias("rest")
.diff.over("team")
.dt.totalDays - 1).cast(int8))
.dropNulls("rest")
.collect
nbShow tidyPl
| game_id | date | variable | team | rest |
|---|---|---|---|---|
| u32 | date | str | str | i8 |
| 5 | 2015-10-28 | "away_team" | "Chicago Bulls" | 0 |
| 6 | 2015-10-28 | "home_team" | "Detroit Pistons" | 0 |
| 11 | 2015-10-28 | "away_team" | "Cleveland Cavaliers" | 0 |
| 14 | 2015-10-28 | "away_team" | "New Orleans Pelicans" | 0 |
| 17 | 2015-10-29 | "away_team" | "Memphis Grizzlies" | 0 |
| … | … | … | … | … |
| 1313 | 2016-06-13 | "home_team" | "Golden State Warriors" | 2 |
| 1314 | 2016-06-16 | "away_team" | "Golden State Warriors" | 2 |
| 1314 | 2016-06-16 | "home_team" | "Cleveland Cavaliers" | 2 |
| 1315 | 2016-06-19 | "away_team" | "Cleveland Cavaliers" | 2 |
| 1315 | 2016-06-19 | "home_team" | "Golden State Warriors" | 2 |
tidy_pl = (
games_pl
.unpivot(
index=["game_id", "date"],
on=["away_team", "home_team"],
value_name="team",
)
.sort("game_id")
.with_columns((
pl.col("date")
.alias("rest")
.diff().over("team")
.dt.total_days() - 1).cast(pl.Int8))
.drop_nulls("rest")
.collect()
)
tidy_pl| game_id | date | variable | team | rest |
|---|---|---|---|---|
| u32 | date | str | str | i8 |
| 5 | 2015-10-28 | "away_team" | "Chicago Bulls" | 0 |
| 6 | 2015-10-28 | "home_team" | "Detroit Pistons" | 0 |
| 11 | 2015-10-28 | "away_team" | "Cleveland Cavaliers" | 0 |
| 14 | 2015-10-28 | "away_team" | "New Orleans Pelicans" | 0 |
| 17 | 2015-10-29 | "away_team" | "Memphis Grizzlies" | 0 |
| … | … | … | … | … |
| 1313 | 2016-06-13 | "home_team" | "Golden State Warriors" | 2 |
| 1314 | 2016-06-16 | "away_team" | "Golden State Warriors" | 2 |
| 1314 | 2016-06-16 | "home_team" | "Cleveland Cavaliers" | 2 |
| 1315 | 2016-06-19 | "away_team" | "Cleveland Cavaliers" | 2 |
| 1315 | 2016-06-19 | "home_team" | "Golden State Warriors" | 2 |
Now we use .pivot so that this days-of-rest data can be added back to the original dataframe.
We'll also add columns for the spread between the home team's rest and away team's rest, and a
flag for whether the home team won.
let byGamePl = tidyPl
.pivot(
values = "rest",
index = ["game_id", "date"],
on = "variable")
.rename({"away_team": "away_rest", "home_team": "home_rest"})
let joinedPl = byGamePl
.join(gamesPl.collect, on = ["game_id", "date"])
.withColumns(
col.home_points.alias("home_win") > col.away_points,
col.home_rest.alias("rest_spread") - col.away_rest)
nbShow joinedPl
| game_id | date | away_rest | home_rest | away_team | away_points | home_team | home_points | home_win | rest_spread |
|---|---|---|---|---|---|---|---|---|---|
| u32 | date | i8 | i8 | str | i64 | str | i64 | bool | i8 |
| 5 | 2015-10-28 | 0 | null | "Chicago Bulls" | 115 | "Brooklyn Nets" | 100 | false | null |
| 6 | 2015-10-28 | null | 0 | "Utah Jazz" | 87 | "Detroit Pistons" | 92 | true | null |
| 11 | 2015-10-28 | 0 | null | "Cleveland Cavaliers" | 106 | "Memphis Grizzlies" | 76 | false | null |
| 14 | 2015-10-28 | 0 | null | "New Orleans Pelicans" | 94 | "Portland Trail Blazers" | 112 | true | null |
| 17 | 2015-10-29 | 0 | 0 | "Memphis Grizzlies" | 112 | "Indiana Pacers" | 103 | false | 0 |
| … | … | … | … | … | … | … | … | … | … |
| 1311 | 2016-06-08 | 2 | 2 | "Golden State Warriors" | 90 | "Cleveland Cavaliers" | 120 | true | 0 |
| 1312 | 2016-06-10 | 1 | 1 | "Golden State Warriors" | 108 | "Cleveland Cavaliers" | 97 | false | 0 |
| 1313 | 2016-06-13 | 2 | 2 | "Cleveland Cavaliers" | 112 | "Golden State Warriors" | 97 | false | 0 |
| 1314 | 2016-06-16 | 2 | 2 | "Golden State Warriors" | 101 | "Cleveland Cavaliers" | 115 | true | 0 |
| 1315 | 2016-06-19 | 2 | 2 | "Cleveland Cavaliers" | 93 | "Golden State Warriors" | 89 | false | 0 |
by_game_pl = (
tidy_pl
.pivot(
values="rest",
index=["game_id", "date"],
on="variable"
)
.rename({"away_team": "away_rest", "home_team": "home_rest"})
)
joined_pl = (
by_game_pl
.join(games_pl.collect(), on=["game_id", "date"])
.with_columns([
pl.col("home_points").alias("home_win") > pl.col("away_points"),
pl.col("home_rest").alias("rest_spread") - pl.col("away_rest"),
])
)
joined_pl| game_id | date | away_rest | home_rest | away_team | away_points | home_team | home_points | home_win | rest_spread |
|---|---|---|---|---|---|---|---|---|---|
| u32 | date | i8 | i8 | str | i64 | str | i64 | bool | i8 |
| 5 | 2015-10-28 | 0 | null | "Chicago Bulls" | 115 | "Brooklyn Nets" | 100 | false | null |
| 6 | 2015-10-28 | null | 0 | "Utah Jazz" | 87 | "Detroit Pistons" | 92 | true | null |
| 11 | 2015-10-28 | 0 | null | "Cleveland Cavaliers" | 106 | "Memphis Grizzlies" | 76 | false | null |
| 14 | 2015-10-28 | 0 | null | "New Orleans Pelicans" | 94 | "Portland Trail Blazers" | 112 | true | null |
| 17 | 2015-10-29 | 0 | 0 | "Memphis Grizzlies" | 112 | "Indiana Pacers" | 103 | false | 0 |
| … | … | … | … | … | … | … | … | … | … |
| 1311 | 2016-06-08 | 2 | 2 | "Golden State Warriors" | 90 | "Cleveland Cavaliers" | 120 | true | 0 |
| 1312 | 2016-06-10 | 1 | 1 | "Golden State Warriors" | 108 | "Cleveland Cavaliers" | 97 | false | 0 |
| 1313 | 2016-06-13 | 2 | 2 | "Cleveland Cavaliers" | 112 | "Golden State Warriors" | 97 | false | 0 |
| 1314 | 2016-06-16 | 2 | 2 | "Golden State Warriors" | 101 | "Cleveland Cavaliers" | 115 | true | 0 |
| 1315 | 2016-06-19 | 2 | 2 | "Cleveland Cavaliers" | 93 | "Golden State Warriors" | 89 | false | 0 |
Here's a lightly edited quote from Modern Pandas:
One somewhat subtle point: an "observation" depends on the question being asked. So really, we have two tidy datasets,
tidyfor answering team-level questions, andjoinedfor answering game-level questions.
The book now plots each team's average days of rest, home and away, and the distribution of
rest_spread:
nbShow joinedPl.valueCounts("rest_spread").dropNulls.sort("rest_spread")
| rest_spread | count |
|---|---|
| i8 | u32 |
| -8 | 3 |
| -3 | 5 |
| -2 | 33 |
| -1 | 189 |
| 0 | 653 |
| … | … |
| 2 | 77 |
| 3 | 14 |
| 4 | 3 |
| 7 | 1 |
| 8 | 1 |
delta_pl = joined_pl["rest_spread"]
delta_pl.value_counts().drop_nulls().sort("rest_spread")| rest_spread | count |
|---|---|
| i8 | u32 |
| -8 | 3 |
| -3 | 5 |
| -2 | 33 |
| -1 | 189 |
| 0 | 653 |
| … | … |
| 2 | 77 |
| 3 | 14 |
| 4 | 3 |
| 7 | 1 |
| 8 | 1 |
Stack / Unstack vs Melt / Pivot
Pandas has special methods stack and unstack for reshaping data with a MultiIndex. Polars
doesn't have an index, so the equivalent Polars code will use melt / pivot.
let restPl = tidyPl
.groupBy("date", "variable")
.agg(col.rest.mean)
nbShow restPl
| date | variable | rest |
|---|---|---|
| date | str | f64 |
| 2015-10-28 | "away_team" | 0.0 |
| 2015-10-28 | "home_team" | 0.0 |
| 2015-10-29 | "away_team" | 0.333333 |
| 2015-10-29 | "home_team" | 0.0 |
| 2015-10-30 | "away_team" | 1.083333 |
| … | … | … |
| 2016-06-13 | "home_team" | 2.0 |
| 2016-06-16 | "away_team" | 2.0 |
| 2016-06-16 | "home_team" | 2.0 |
| 2016-06-19 | "away_team" | 2.0 |
| 2016-06-19 | "home_team" | 2.0 |
rest_pl = (
tidy_pl
.group_by(["date", "variable"], maintain_order=True)
.agg(pl.col("rest").mean())
)
rest_pl| date | variable | rest |
|---|---|---|
| date | str | f64 |
| 2015-10-28 | "away_team" | 0.0 |
| 2015-10-28 | "home_team" | 0.0 |
| 2015-10-29 | "away_team" | 0.333333 |
| 2015-10-29 | "home_team" | 0.0 |
| 2015-10-30 | "away_team" | 1.083333 |
| … | … | … |
| 2016-06-13 | "home_team" | 2.0 |
| 2016-06-16 | "away_team" | 2.0 |
| 2016-06-16 | "home_team" | 2.0 |
| 2016-06-19 | "away_team" | 2.0 |
| 2016-06-19 | "home_team" | 2.0 |
In Polars we use .pivot to do what in Pandas would require .unstack:
nbShow restPl.pivot(index = "date", on = "variable", values = "rest")
| date | away_team | home_team |
|---|---|---|
| date | f64 | f64 |
| 2015-10-28 | 0.0 | 0.0 |
| 2015-10-29 | 0.333333 | 0.0 |
| 2015-10-30 | 1.083333 | 0.916667 |
| 2015-10-31 | 0.166667 | 0.833333 |
| 2015-11-01 | 1.142857 | 1.0 |
| … | … | … |
| 2016-06-08 | 2.0 | 2.0 |
| 2016-06-10 | 1.0 | 1.0 |
| 2016-06-13 | 2.0 | 2.0 |
| 2016-06-16 | 2.0 | 2.0 |
| 2016-06-19 | 2.0 | 2.0 |
rest_pl.pivot(index="date", on="variable", values="rest")| date | away_team | home_team |
|---|---|---|
| date | f64 | f64 |
| 2015-10-28 | 0.0 | 0.0 |
| 2015-10-29 | 0.333333 | 0.0 |
| 2015-10-30 | 1.083333 | 0.916667 |
| 2015-10-31 | 0.166667 | 0.833333 |
| 2015-11-01 | 1.142857 | 1.0 |
| … | … | … |
| 2016-06-08 | 2.0 | 2.0 |
| 2016-06-10 | 1.0 | 1.0 |
| 2016-06-13 | 2.0 | 2.0 |
| 2016-06-16 | 2.0 | 2.0 |
| 2016-06-19 | 2.0 | 2.0 |
The moving average of rest days, which the book plots:
nbShow restPl.pivot(index = "date", values = "rest", on = "variable")
.filter(col.away_team < 7)
.sort("date")
.select(col.date, col(float).rollingMean(7))
| date | away_team | home_team |
|---|---|---|
| date | f64 | f64 |
| 2015-10-28 | null | null |
| 2015-10-29 | null | null |
| 2015-10-30 | null | null |
| 2015-10-31 | null | null |
| 2015-11-01 | null | null |
| … | … | … |
| 2016-06-08 | 1.857143 | 1.428571 |
| 2016-06-10 | 1.857143 | 1.428571 |
| 2016-06-13 | 2.0 | 1.571429 |
| 2016-06-16 | 2.142857 | 1.714286 |
| 2016-06-19 | 2.285714 | 1.857143 |
(
rest_pl.pivot(index="date", values="rest", on="variable")
.filter(pl.col("away_team") < 7)
.sort("date")
.select([pl.col("date"), pl.col(pl.Float64).rolling_mean(7)])
)| date | away_team | home_team |
|---|---|---|
| date | f64 | f64 |
| 2015-10-28 | null | null |
| 2015-10-29 | null | null |
| 2015-10-30 | null | null |
| 2015-10-31 | null | null |
| 2015-11-01 | null | null |
| … | … | … |
| 2016-06-08 | 1.857143 | 1.428571 |
| 2016-06-10 | 1.857143 | 1.428571 |
| 2016-06-13 | 2.0 | 1.571429 |
| 2016-06-16 | 2.142857 | 1.714286 |
| 2016-06-19 | 2.285714 | 1.857143 |
Mini Project: Home Court Advantage?
We may as well do some (not very rigorous) analysis: let's see if home advantage is a real thing.
Find the win percent for each team
We want to control for the strength of the teams playing. The team's victory percentage is probably not a good control but it's what we'll use:
let winCol = col.win
let winsPl = joinedPl.unpivot(
index = ["game_id", "date", "home_win"],
valueName = "team",
variableName = "is_home",
on = ["home_team", "away_team"])
.withColumns(col.home_win.alias("win") == (col.is_home == "home_team"))
.groupBy("team", "is_home")
.agg(
winCol.sum.alias("n_wins"),
winCol.count.alias("n_games"),
winCol.mean.alias("win_pct"))
.sort(["team", "is_home"])
nbShow winsPl
| team | is_home | n_wins | n_games | win_pct |
|---|---|---|---|---|
| str | str | u32 | u32 | f64 |
| "Atlanta Hawks" | "away_team" | 22 | 46 | 0.478261 |
| "Atlanta Hawks" | "home_team" | 30 | 45 | 0.666667 |
| "Boston Celtics" | "away_team" | 20 | 44 | 0.454545 |
| "Boston Celtics" | "home_team" | 29 | 43 | 0.674419 |
| "Brooklyn Nets" | "away_team" | 7 | 41 | 0.170732 |
| … | … | … | … | … |
| "Toronto Raptors" | "home_team" | 39 | 51 | 0.764706 |
| "Utah Jazz" | "away_team" | 16 | 41 | 0.390244 |
| "Utah Jazz" | "home_team" | 24 | 41 | 0.585366 |
| "Washington Wizards" | "away_team" | 18 | 40 | 0.45 |
| "Washington Wizards" | "home_team" | 22 | 41 | 0.536585 |
win_col = pl.col("win")
wins_pl = (
joined_pl.unpivot(
index=["game_id", "date", "home_win"],
value_name="team",
variable_name="is_home",
on=["home_team", "away_team"],
)
.with_columns(pl.col("home_win").alias("win") == (pl.col("is_home") == "home_team"))
.group_by(["team", "is_home"])
.agg(
[
win_col.sum().alias("n_wins"),
win_col.count().alias("n_games"),
win_col.mean().alias("win_pct"),
]
)
.sort(["team", "is_home"])
)
wins_pl| team | is_home | n_wins | n_games | win_pct |
|---|---|---|---|---|
| str | str | u32 | u32 | f64 |
| "Atlanta Hawks" | "away_team" | 22 | 46 | 0.478261 |
| "Atlanta Hawks" | "home_team" | 30 | 45 | 0.666667 |
| "Boston Celtics" | "away_team" | 20 | 44 | 0.454545 |
| "Boston Celtics" | "home_team" | 29 | 43 | 0.674419 |
| "Brooklyn Nets" | "away_team" | 7 | 41 | 0.170732 |
| … | … | … | … | … |
| "Toronto Raptors" | "home_team" | 39 | 51 | 0.764706 |
| "Utah Jazz" | "away_team" | 16 | 41 | 0.390244 |
| "Utah Jazz" | "home_team" | 24 | 41 | 0.585366 |
| "Washington Wizards" | "away_team" | 18 | 40 | 0.45 |
| "Washington Wizards" | "home_team" | 22 | 41 | 0.536585 |
Now we calculate the win percent by team, regardless of whether they're home or away:
let winPercentPl = winsPl.groupBy("team").agg(
col.n_wins.sum.alias("win_pct") / col.n_games.sum)
nbShow winPercentPl
| team | win_pct |
|---|---|
| str | f64 |
| "Atlanta Hawks" | 0.571429 |
| "Boston Celtics" | 0.563218 |
| "Brooklyn Nets" | 0.256098 |
| "Charlotte Hornets" | 0.579545 |
| "Chicago Bulls" | 0.506173 |
| … | … |
| "Sacramento Kings" | 0.407407 |
| "San Antonio Spurs" | 0.802198 |
| "Toronto Raptors" | 0.643564 |
| "Utah Jazz" | 0.487805 |
| "Washington Wizards" | 0.493827 |
win_percent_pl = (
wins_pl.group_by("team", maintain_order=True).agg(
pl.col("n_wins").sum().alias("win_pct") / pl.col("n_games").sum()
)
)
win_percent_pl| team | win_pct |
|---|---|
| str | f64 |
| "Atlanta Hawks" | 0.571429 |
| "Boston Celtics" | 0.563218 |
| "Brooklyn Nets" | 0.256098 |
| "Charlotte Hornets" | 0.579545 |
| "Chicago Bulls" | 0.506173 |
| … | … |
| "Sacramento Kings" | 0.407407 |
| "San Antonio Spurs" | 0.802198 |
| "Toronto Raptors" | 0.643564 |
| "Utah Jazz" | 0.487805 |
| "Washington Wizards" | 0.493827 |
The book plots these as bars, and then home court advantage against overall win percentage:
let winsToPlotPl = winsPl.pivot(index = "team", on = "is_home", values = "win_pct")
.withColumns(
col.home_team.alias("Home Win % - Away %") - col.away_team,
(col.home_team.alias("Overall %") + col.away_team) / 2)
nbShow winsToPlotPl
| team | away_team | home_team | Home Win % - Away % | Overall % |
|---|---|---|---|---|
| str | f64 | f64 | f64 | f64 |
| "Atlanta Hawks" | 0.478261 | 0.666667 | 0.188406 | 0.572464 |
| "Boston Celtics" | 0.454545 | 0.674419 | 0.219873 | 0.564482 |
| "Brooklyn Nets" | 0.170732 | 0.341463 | 0.170732 | 0.256098 |
| "Charlotte Hornets" | 0.431818 | 0.727273 | 0.295455 | 0.579545 |
| "Chicago Bulls" | 0.390244 | 0.625 | 0.234756 | 0.507622 |
| … | … | … | … | … |
| "Sacramento Kings" | 0.365854 | 0.45 | 0.084146 | 0.407927 |
| "San Antonio Spurs" | 0.666667 | 0.934783 | 0.268116 | 0.800725 |
| "Toronto Raptors" | 0.52 | 0.764706 | 0.244706 | 0.642353 |
| "Utah Jazz" | 0.390244 | 0.585366 | 0.195122 | 0.487805 |
| "Washington Wizards" | 0.45 | 0.536585 | 0.086585 | 0.493293 |
wins_to_plot_pl = (
wins_pl.pivot(index="team", on="is_home", values="win_pct")
.with_columns(
[
pl.col("home_team").alias("Home Win % - Away %") - pl.col("away_team"),
(pl.col("home_team").alias("Overall %") + pl.col("away_team")) / 2,
]
)
)
wins_to_plot_pl| team | away_team | home_team | Home Win % - Away % | Overall % |
|---|---|---|---|---|
| str | f64 | f64 | f64 | f64 |
| "Atlanta Hawks" | 0.478261 | 0.666667 | 0.188406 | 0.572464 |
| "Boston Celtics" | 0.454545 | 0.674419 | 0.219873 | 0.564482 |
| "Brooklyn Nets" | 0.170732 | 0.341463 | 0.170732 | 0.256098 |
| "Charlotte Hornets" | 0.431818 | 0.727273 | 0.295455 | 0.579545 |
| "Chicago Bulls" | 0.390244 | 0.625 | 0.234756 | 0.507622 |
| … | … | … | … | … |
| "Sacramento Kings" | 0.365854 | 0.45 | 0.084146 | 0.407927 |
| "San Antonio Spurs" | 0.666667 | 0.934783 | 0.268116 | 0.800725 |
| "Toronto Raptors" | 0.52 | 0.764706 | 0.244706 | 0.642353 |
| "Utah Jazz" | 0.390244 | 0.585366 | 0.195122 | 0.487805 |
| "Washington Wizards" | 0.45 | 0.536585 | 0.086585 | 0.493293 |
Let's add the win percent back to the dataframe and run a regression:
let regDfPl = joinedPl.join(winPercentPl, leftOn = ["home_team"], rightOn = ["team"])
.rename({"win_pct": "home_strength"})
.join(winPercentPl, leftOn = ["away_team"], rightOn = ["team"])
.rename({"win_pct": "away_strength"})
.withColumns(
col.home_points.alias("point_diff") - col.away_points,
col.home_rest.alias("rest_diff") - col.away_rest,
col.home_win.cast(uint8)) # for statsmodels
nbShow regDfPl.sort("game_id").head
| game_id | date | away_rest | home_rest | away_team | away_points | home_team | home_points | home_win | rest_spread | home_strength | away_strength | point_diff | rest_diff |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| u32 | date | i8 | i8 | str | i64 | str | i64 | u8 | i8 | f64 | f64 | i64 | i8 |
| 5 | 2015-10-28 | 0 | null | "Chicago Bulls" | 115 | "Brooklyn Nets" | 100 | 0 | null | 0.256098 | 0.506173 | -15 | null |
| 6 | 2015-10-28 | null | 0 | "Utah Jazz" | 87 | "Detroit Pistons" | 92 | 1 | null | 0.505882 | 0.487805 | 5 | null |
| 11 | 2015-10-28 | 0 | null | "Cleveland Cavaliers" | 106 | "Memphis Grizzlies" | 76 | 0 | null | 0.488372 | 0.715686 | -30 | null |
| 14 | 2015-10-28 | 0 | null | "New Orleans Pelicans" | 94 | "Portland Trail Blazers" | 112 | 1 | null | 0.526882 | 0.37037 | 18 | null |
| 17 | 2015-10-29 | 0 | 0 | "Memphis Grizzlies" | 112 | "Indiana Pacers" | 103 | 0 | 0 | 0.545455 | 0.488372 | -9 | 0 |
reg_df_pl = (
joined_pl.join(win_percent_pl, left_on="home_team", right_on="team")
.rename({"win_pct": "home_strength"})
.join(win_percent_pl, left_on="away_team", right_on="team")
.rename({"win_pct": "away_strength"})
.with_columns(
[
pl.col("home_points").alias("point_diff") - pl.col("away_points"),
pl.col("home_rest").alias("rest_diff") - pl.col("away_rest"),
pl.col("home_win").cast(pl.UInt8), # for statsmodels
]
)
)
reg_df_pl.sort("game_id").head()| game_id | date | away_rest | home_rest | away_team | away_points | home_team | home_points | home_win | rest_spread | home_strength | away_strength | point_diff | rest_diff |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| u32 | date | i8 | i8 | str | i64 | str | i64 | u8 | i8 | f64 | f64 | i64 | i8 |
| 5 | 2015-10-28 | 0 | null | "Chicago Bulls" | 115 | "Brooklyn Nets" | 100 | 0 | null | 0.256098 | 0.506173 | -15 | null |
| 6 | 2015-10-28 | null | 0 | "Utah Jazz" | 87 | "Detroit Pistons" | 92 | 1 | null | 0.505882 | 0.487805 | 5 | null |
| 11 | 2015-10-28 | 0 | null | "Cleveland Cavaliers" | 106 | "Memphis Grizzlies" | 76 | 0 | null | 0.488372 | 0.715686 | -30 | null |
| 14 | 2015-10-28 | 0 | null | "New Orleans Pelicans" | 94 | "Portland Trail Blazers" | 112 | 1 | null | 0.526882 | 0.37037 | 18 | null |
| 17 | 2015-10-29 | 0 | 0 | "Memphis Grizzlies" | 112 | "Indiana Pacers" | 103 | 0 | 0 | 0.545455 | 0.488372 | -9 | 0 |
Summary
This was mostly a demonstration of .pivot and .melt, with several different examples of
reshaping data in Polars.
import nanuqbook
bookInit()
nbText: "# Reshaping and Tidy Data"
attribution modernPolars("Reshaping and Tidy Data", "tidy",
"The data is the book's NBA 2015-16 results (scraped from basketball-reference.com by the " &
"book), read from `data/modern-polars/nba/`; the scraping code is left out. Plots and the " &
"statsmodels regression are left out, and tables show 10 rows instead of 5.")
nbText: """
There's a [whole paper](https://vita.had.co.nz/papers/tidy-data.pdf) by Hadley Wickham about
tidy data but it's in a PDF so you're probably not going to read it. Here's the paper's
definition of tidy data:
1. Each variable forms a column.
2. Each observation forms a row.
3. Each type of observational unit forms a table.
As Dr Wickham notes, this is [Codd's 3rd Normal Form](https://en.wikipedia.org/wiki/Third_normal_form)
but in statspeak rather than databasespeak.
The meaning of "variable" and "observation" depend on what we're studying, so tidy data is a
concept that you mostly learn through experience and β¨vibesβ¨.
Now we'll explore what tidy data looks like for an NBA results dataset.
## Get the data
"""
tabs """
import polars as pl
nba_glob = "data/modern-polars/nba/*.csv"
pl.scan_csv(nba_glob).head().collect()
""":
nbCode:
import nanuq
let nbaGlob = "data/modern-polars/nba/*.csv"
nbShow scanCsv(nbaGlob).head.collect
nanuq """
The book downloads one page per month of the 2015-16 season with `pd.read_html`, keeps five
columns under new names, and saves each month as a CSV, messy on purpose. The port starts from
those CSVs.
"""
nbText: """
## Cleaning π§Ή
Nothing super interesting here:
"""
tabs """
games_pl = (
pl.scan_csv(nba_glob)
.with_columns(
pl.col("date").str.strptime(pl.Date, "%a, %b %d, %Y"),
)
.sort("date")
.with_row_index("game_id")
)
games_pl.head().collect()
""":
nbCode:
let gamesPl = scanCsv(nbaGlob)
.withColumns(
col.date.str.strptime(Date, "%a, %b %d, %Y"))
.sort("date")
.withRowIndex("game_id")
nbShow gamesPl.head.collect
nbText: """
Polars does have a
[`drop_nulls`](https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.drop_nulls.html)
method but the only parameter it takes is `subset`, which lets you consider null values just for
a subset of the columns. Polars `drop_nulls` will drop the row if *any* values are null. If you
only want to drop when all values are null, the docs recommend
`.filter(~pl.all_horizontal(pl.all().is_null()))`.
A previous version of the Polars example used
[`pl.fold`](https://docs.pola.rs/user-guide/expressions/folds/), which is for fast horizontal
operations. It doesn't come up anywhere else in this book, so consider this your warning that it
exists.
## Pivot and Melt
Here's a simple explanation of `pivot`ing and `melt`ing. If you already know what pivot and
melt are, feel free to scroll past this bit.
### Pivot
Suppose you have a dataframe that looks like this:
"""
tabs """
from datetime import date
prices = pl.DataFrame({
"date": [*[date(2020, 1, 1)]*4, *[date(2020, 1, 2)]*4, *[date(2020, 1, 3)]*4],
"ticker": [*["AAPL", "TSLA", "MSFT", "NFLX"]*3],
"price": [100, 200, 300, 400, 110, 220, 330, 420, 105, 210, 315, 440],
})
prices
""":
nbCode:
import std/sequtils
let prices = newDataFrame(
series("date", sequtils.repeat(date(2020, 1, 1), 4) & sequtils.repeat(date(2020, 1, 2), 4) &
sequtils.repeat(date(2020, 1, 3), 4)),
series("ticker", cycle(["AAPL", "TSLA", "MSFT", "NFLX"], 3)),
series("price", [100, 200, 300, 400, 110, 220, 330, 420, 105, 210, 315, 440]))
nbShow prices
nbText: """
You can call `df.pivot` to get a dataframe that looks like this:
"""
tabs """
pivoted = prices.pivot(index="date", values="price", on="ticker")
pivoted
""":
nbCode:
let pivoted = prices.pivot(index = "date", values = "price", on = "ticker")
nbShow pivoted
nbText: """
As you can see, `.pivot` creates a dataframe where the columns are the unique labels from one
column ("ticker"), alongside the index column ("date"). The values for the non-index columns are
taken from the corresponding rows of the `values` column ("price").
If our dataframe had multiple prices for the same ticker on the same date, we would use the
`aggregate_function` parameter of the `.pivot` method, e.g.:
`prices.pivot(..., aggregate_function="mean")`. Pivoting with an aggregate function gives us
similar behaviour to what Excel calls "pivot tables".
### Melt / Unpivot
Melt is the inverse of pivot. While pivot takes us from *long* data to *wide* data, melt goes
from wide to long.
Note: Polars has recently replaced its `melt` method with an `unpivot` method.
If we call `.unpivot(index="date", value_name="price")` on our pivoted dataframe we get our
original dataframe back:
"""
tabs """
pivoted.unpivot(index="date", value_name="price")
""":
nbCode:
nbShow pivoted.unpivot(index = "date", valueName = "price")
nbText: """
## Tidy NBA data
Suppose we want to calculate the days of rest each team had before each game. In the current
structure this is difficult because we need to track both the `home_team` and `away_team`
columns. We'll use `.unpivot` so that there's a single `team` column. This makes it easier to
add a `rest` column with the per-team rest days between games.
"""
tabs """
tidy_pl = (
games_pl
.unpivot(
index=["game_id", "date"],
on=["away_team", "home_team"],
value_name="team",
)
.sort("game_id")
.with_columns((
pl.col("date")
.alias("rest")
.diff().over("team")
.dt.total_days() - 1).cast(pl.Int8))
.drop_nulls("rest")
.collect()
)
tidy_pl
""":
nbCode:
let tidyPl = gamesPl
.unpivot(
index = ["game_id", "date"],
on = ["away_team", "home_team"],
valueName = "team")
.sort("game_id")
.withColumns((
col.date
.alias("rest")
.diff.over("team")
.dt.totalDays - 1).cast(int8))
.dropNulls("rest")
.collect
nbShow tidyPl
nbText: """
Now we use `.pivot` so that this days-of-rest data can be added back to the original dataframe.
We'll also add columns for the spread between the home team's rest and away team's rest, and a
flag for whether the home team won.
"""
tabs """
by_game_pl = (
tidy_pl
.pivot(
values="rest",
index=["game_id", "date"],
on="variable"
)
.rename({"away_team": "away_rest", "home_team": "home_rest"})
)
joined_pl = (
by_game_pl
.join(games_pl.collect(), on=["game_id", "date"])
.with_columns([
pl.col("home_points").alias("home_win") > pl.col("away_points"),
pl.col("home_rest").alias("rest_spread") - pl.col("away_rest"),
])
)
joined_pl
""":
nbCode:
let byGamePl = tidyPl
.pivot(
values = "rest",
index = ["game_id", "date"],
on = "variable")
.rename({"away_team": "away_rest", "home_team": "home_rest"})
let joinedPl = byGamePl
.join(gamesPl.collect, on = ["game_id", "date"])
.withColumns(
col.home_points.alias("home_win") > col.away_points,
col.home_rest.alias("rest_spread") - col.away_rest)
nbShow joinedPl
nbText: """
Here's a lightly edited quote from *Modern Pandas*:
> One somewhat subtle point: an "observation" depends on the question being asked. So really,
> we have two tidy datasets, `tidy` for answering team-level questions, and `joined` for
> answering game-level questions.
The book now plots each team's average days of rest, home and away, and the distribution of
`rest_spread`:
"""
tabs """
delta_pl = joined_pl["rest_spread"]
delta_pl.value_counts().drop_nulls().sort("rest_spread")
""":
nbCode:
nbShow joinedPl.valueCounts("rest_spread").dropNulls.sort("rest_spread")
nanuq """
The book draws this as a bar chart (with seaborn and matplotlib, which the port leaves out),
and then the home team's win rate for each `rest_spread` between -3 and 3. The port shows the
counts the first chart is made of.
"""
nbText: """
## Stack / Unstack vs Melt / Pivot
Pandas has special methods `stack` and `unstack` for reshaping data with a MultiIndex. Polars
doesn't have an index, so the equivalent Polars code will use `melt` / `pivot`.
"""
tabs """
rest_pl = (
tidy_pl
.group_by(["date", "variable"], maintain_order=True)
.agg(pl.col("rest").mean())
)
rest_pl
""":
nbCode:
let restPl = tidyPl
.groupBy("date", "variable")
.agg(col.rest.mean)
nbShow restPl
nbText: """
In Polars we use `.pivot` to do what in Pandas would require `.unstack`:
"""
tabs """
rest_pl.pivot(index="date", on="variable", values="rest")
""":
nbCode:
nbShow restPl.pivot(index = "date", on = "variable", values = "rest")
nbText: """
The moving average of rest days, which the book plots:
"""
tabs """
(
rest_pl.pivot(index="date", values="rest", on="variable")
.filter(pl.col("away_team") < 7)
.sort("date")
.select([pl.col("date"), pl.col(pl.Float64).rolling_mean(7)])
)
""":
nbCode:
nbShow restPl.pivot(index = "date", values = "rest", on = "variable")
.filter(col.away_team < 7)
.sort("date")
.select(col.date, col(float).rollingMean(7))
nbText: """
## Mini Project: Home Court Advantage?
We may as well do some (not very rigorous) analysis: let's see if home advantage is a real
thing.
### Find the win percent for each team
We want to control for the strength of the teams playing. The team's victory percentage is
probably not a good control but it's what we'll use:
"""
tabs """
win_col = pl.col("win")
wins_pl = (
joined_pl.unpivot(
index=["game_id", "date", "home_win"],
value_name="team",
variable_name="is_home",
on=["home_team", "away_team"],
)
.with_columns(pl.col("home_win").alias("win") == (pl.col("is_home") == "home_team"))
.group_by(["team", "is_home"])
.agg(
[
win_col.sum().alias("n_wins"),
win_col.count().alias("n_games"),
win_col.mean().alias("win_pct"),
]
)
.sort(["team", "is_home"])
)
wins_pl
""":
nbCode:
let winCol = col.win
let winsPl = joinedPl.unpivot(
index = ["game_id", "date", "home_win"],
valueName = "team",
variableName = "is_home",
on = ["home_team", "away_team"])
.withColumns(col.home_win.alias("win") == (col.is_home == "home_team"))
.groupBy("team", "is_home")
.agg(
winCol.sum.alias("n_wins"),
winCol.count.alias("n_games"),
winCol.mean.alias("win_pct"))
.sort(["team", "is_home"])
nbShow winsPl
nbText: """
Now we calculate the win percent by team, regardless of whether they're home or away:
"""
tabs """
win_percent_pl = (
wins_pl.group_by("team", maintain_order=True).agg(
pl.col("n_wins").sum().alias("win_pct") / pl.col("n_games").sum()
)
)
win_percent_pl
""":
nbCode:
let winPercentPl = winsPl.groupBy("team").agg(
col.n_wins.sum.alias("win_pct") / col.n_games.sum)
nbShow winPercentPl
nbText: """
The book plots these as bars, and then home court advantage against overall win percentage:
"""
tabs """
wins_to_plot_pl = (
wins_pl.pivot(index="team", on="is_home", values="win_pct")
.with_columns(
[
pl.col("home_team").alias("Home Win % - Away %") - pl.col("away_team"),
(pl.col("home_team").alias("Overall %") + pl.col("away_team")) / 2,
]
)
)
wins_to_plot_pl
""":
nbCode:
let winsToPlotPl = winsPl.pivot(index = "team", on = "is_home", values = "win_pct")
.withColumns(
col.home_team.alias("Home Win % - Away %") - col.away_team,
(col.home_team.alias("Overall %") + col.away_team) / 2)
nbShow winsToPlotPl
nbText: """
Let's add the win percent back to the dataframe and run a regression:
"""
tabs """
reg_df_pl = (
joined_pl.join(win_percent_pl, left_on="home_team", right_on="team")
.rename({"win_pct": "home_strength"})
.join(win_percent_pl, left_on="away_team", right_on="team")
.rename({"win_pct": "away_strength"})
.with_columns(
[
pl.col("home_points").alias("point_diff") - pl.col("away_points"),
pl.col("home_rest").alias("rest_diff") - pl.col("away_rest"),
pl.col("home_win").cast(pl.UInt8), # for statsmodels
]
)
)
reg_df_pl.sort("game_id").head()
""":
nbCode:
let regDfPl = joinedPl.join(winPercentPl, leftOn = ["home_team"], rightOn = ["team"])
.rename({"win_pct": "home_strength"})
.join(winPercentPl, leftOn = ["away_team"], rightOn = ["team"])
.rename({"win_pct": "away_strength"})
.withColumns(
col.home_points.alias("point_diff") - col.away_points,
col.home_rest.alias("rest_diff") - col.away_rest,
col.home_win.cast(uint8)) # for statsmodels
nbShow regDfPl.sort("game_id").head
nanuq """
The book fits a logit model with statsmodels
(`home_win ~ home_strength + away_strength + home_rest + away_rest`) on this frame; that step is
Python's, so the port stops at the frame. Both tabs sort by `game_id` before `head`: a join does
not keep any row order unless asked to, so the first five rows would differ.
"""
nbText: """
## Summary
This was mostly a demonstration of `.pivot` and `.melt`, with several different examples of
reshaping data in Polars.
"""
bookSave()
On GitHub: book/modern-polars/tidy.nim