Skip to main content

Men's college basketball — additional Python functions — Analytics: ncaa_coach–weighted_avg

ncaa_coach_stints​

ncaa_coach_stints(coaches: 'pl.DataFrame', records: 'pl.DataFrame') -> 'pl.DataFrame'

The card coach of each team-season as a whole-season stint, unless the card says the season changed hands.

A card whose season record (coach_season_records) is short of the team's by more than a game and more than a loss marks a mid-season change, and its figures are not the card coach's own games: on Sports-Reference they are the other coach's (Ole Miss 2017-18's card names Andy Kennedy with 1-4, Tony Madlock's five games; Kennedy went 11-16). Such a team-season gets no stint, so it stays uncredited (and is counted in a log line). Otherwise -- the record matches, is a loss off, drops vacated wins (never losses), or cannot be computed -- the card coach has the whole season.

Parameters

ParameterTypeDefaultDescription
coachesDataFramencaa_team_coaches rows, with the season before each wanted one for the record difference.
recordsDataFrameThe teams' season records: season, team_id, games, losses (as sportsdataverse._common.team_luck.season_records gives them).

Returns

Stints in ~sportsdataverse._common.coach_seasons.STINTS_SCHEMA with no counts and position="any", one per team-season with a card, an ESPN team id (cards with none are counted in a log line) and no mid-season change.

col_nametypedescription
seasonInt64Season, named by the year it ends (2025 is 2024-25).
team_idInt64ESPN team id of the school (from the card's NCAA team-season crosswalk).
coach_idInt64NCAA person id of the card's head coach (stats.ncaa.org /people/{id}).
coachStringHead coach's name on the card.
gamesInt64Always null here; the card coach has the whole season (a season the card shows changing hands has no stint).
winsInt64Always null here, as games.
positionStringAlways any; one whole-season stint per team-season.

Raises

ExceptionDescription
ValueErrorIf two cards name a coach for the same (season, team_id).

ncaa_impact_rows​

ncaa_impact_rows(pbp: 'pl.DataFrame', possessions: 'pl.DataFrame', *, league: 'str' = 'mens') -> 'pl.DataFrame'

Map the stats.ncaa.org pbp and possessions onto the game-impact row frame.

One row per event (the clock since the previous event in the period and the points scored on it, on that event's lineup; a free throw on the lineup at the last foul) and one per possession (its lineup and which side had it, poss_team == home). The clock left in a period after its last event goes to that event's lineup, so each period's clock is whole. The possessions of a contest with no pbp events, and those whose poss_team is neither side, are dropped.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameload_ncaa_mbb_pbp / load_ncaa_wbb_pbp rows, in release (game) order, with the cumulative game_seconds and the period.
possessionsDataFrameload_ncaa_mbb_possessions / load_ncaa_wbb_possessions rows.
leaguestr'mens'"mens" (20-minute halves) or "womens" (10-minute quarters from 2016, halves before); overtimes are 5 minutes.

Returns

Rows in sportsdataverse._common.game_impact.impact_row_schema with String player ids.

col_nametypedescription
seasonInt64Season of the action or possession.
game_idStringstats.ncaa.org contest id.
home_team_idInt64Home ESPN team id (null for a non-D1 team).
away_team_idInt64Away ESPN team id (null for a non-D1 team).
home_1StringHome player 1 on the floor (on a free throw, the player on the floor at the last foul).
home_2StringHome player 2 on the floor (on a free throw, the player on the floor at the last foul).
home_3StringHome player 3 on the floor (on a free throw, the player on the floor at the last foul).
home_4StringHome player 4 on the floor (on a free throw, the player on the floor at the last foul).
home_5StringHome player 5 on the floor (on a free throw, the player on the floor at the last foul).
away_1StringAway player 1 on the floor (on a free throw, the player on the floor at the last foul).
away_2StringAway player 2 on the floor (on a free throw, the player on the floor at the last foul).
away_3StringAway player 3 on the floor (on a free throw, the player on the floor at the last foul).
away_4StringAway player 4 on the floor (on a free throw, the player on the floor at the last foul).
away_5StringAway player 5 on the floor (on a free throw, the player on the floor at the last foul).
secondsFloat64Game clock that ran into this action (0 on a possession row).
home_ptsInt64Points the home team scored on this action (0 on a possession row).
away_ptsInt64Points the away team scored on this action (0 on a possession row).
home_possInt641 on a possession row where the home team has the ball, else 0.
away_possInt641 on a possession row where the away team has the ball, else 0.

Raises

ExceptionDescription
ValueErrorIf league is not "mens" or "womens".

Example

from sportsdataverse.mbb.mbb_loaders import load_ncaa_mbb_pbp, load_ncaa_mbb_possessions
from sportsdataverse.mbb.mbb_game_impact import ncaa_impact_rows
rows = ncaa_impact_rows(load_ncaa_mbb_pbp(2025), load_ncaa_mbb_possessions(2025))

ncaa_lineup_count_rows​

ncaa_lineup_count_rows(pbp: 'pl.DataFrame') -> 'pl.DataFrame'

Map the stats.ncaa.org pbp onto the lineup-seasons count frame.

Each shot, free throw, rebound and turnover counts for the side whose event_team it is, on the lineup at the event; a free throw on the lineup at the most recent foul (sportsdataverse._common.game_impact.credit_free_throws_to_foul_lineup). Events with no count are dropped.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameload_ncaa_mbb_pbp / load_ncaa_wbb_pbp rows, in release (game) order.

Returns

One row per counted event in sportsdataverse._common.lineup_seasons.lineup_count_schema (with the shot zones) and String player ids.

col_nametypedescription
seasonInt64Season, named by the year it ends.
game_idStringstats.ncaa.org contest id.
home_team_idInt64ESPN team id of the home side.
away_team_idInt64ESPN team id of the away side.
home_1Stringstats.ncaa.org id of home player 1 on the floor at the event (a free throw: at the last foul).
home_2Stringstats.ncaa.org id of home player 2 on the floor at the event (a free throw: at the last foul).
home_3Stringstats.ncaa.org id of home player 3 on the floor at the event (a free throw: at the last foul).
home_4Stringstats.ncaa.org id of home player 4 on the floor at the event (a free throw: at the last foul).
home_5Stringstats.ncaa.org id of home player 5 on the floor at the event (a free throw: at the last foul).
away_1Stringstats.ncaa.org id of away player 1 on the floor at the event (a free throw: at the last foul).
away_2Stringstats.ncaa.org id of away player 2 on the floor at the event (a free throw: at the last foul).
away_3Stringstats.ncaa.org id of away player 3 on the floor at the event (a free throw: at the last foul).
away_4Stringstats.ncaa.org id of away player 4 on the floor at the event (a free throw: at the last foul).
away_5Stringstats.ncaa.org id of away player 5 on the floor at the event (a free throw: at the last foul).
home_fgaInt64The home side's field-goal attempts on the event (0 or 1).
home_fgmInt64The home side's field goals made on the event (0 or 1).
home_fg3aInt64The home side's three-point attempts on the event (0 or 1).
home_fg3mInt64The home side's threes made on the event (0 or 1).
home_ftaInt64The home side's free-throw attempts on the event (0 or 1).
home_orebInt64The home side's offensive rebounds on the event (0 or 1).
home_drebInt64The home side's defensive rebounds on the event (0 or 1).
home_tovInt64The home side's turnovers on the event (0 or 1).
home_rimaInt64The home side's rim attempts on the event (0 or 1).
home_rimmInt64The home side's rim makes on the event (0 or 1).
home_midaInt64The home side's mid-range attempts on the event (0 or 1).
home_midmInt64The home side's mid-range makes on the event (0 or 1).
away_fgaInt64The away side's field-goal attempts on the event (0 or 1).
away_fgmInt64The away side's field goals made on the event (0 or 1).
away_fg3aInt64The away side's three-point attempts on the event (0 or 1).
away_fg3mInt64The away side's threes made on the event (0 or 1).
away_ftaInt64The away side's free-throw attempts on the event (0 or 1).
away_orebInt64The away side's offensive rebounds on the event (0 or 1).
away_drebInt64The away side's defensive rebounds on the event (0 or 1).
away_tovInt64The away side's turnovers on the event (0 or 1).
away_rimaInt64The away side's rim attempts on the event (0 or 1).
away_rimmInt64The away side's rim makes on the event (0 or 1).
away_midaInt64The away side's mid-range attempts on the event (0 or 1).
away_midmInt64The away side's mid-range makes on the event (0 or 1).

Example

from sportsdataverse.mbb.mbb_loaders import load_ncaa_mbb_pbp
from sportsdataverse.mbb.mbb_lineup_seasons import ncaa_lineup_count_rows
rows = ncaa_lineup_count_rows(load_ncaa_mbb_pbp(2025))

ncaa_mbb_lineups​

ncaa_mbb_lineups(pbp: 'pl.DataFrame', *, include_transition: 'bool' = False, fix_tip_in: 'bool' = True, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'

Aggregate bigballR-contract play-by-play into per-lineup stats.

Port of bigballR get_lineups (all_functions.R:1945-2521). Rows with any missing on-court player and substitution rows are dropped, each row's home/away five are byte-sorted so a lineup always occupies the same columns, and the home + away passes are combined per (p1..p5, team). Ratios are derived from the summed counters, rounded to 3 decimals, and NA/Inf are zeroed exactly where R does it.

Parameters

ParameterTypeDefaultDescription
pbpDataFramePlay-by-play frame in the sdv-py 35-column snake_case bigballR contract (parse_ncaa_bb_game_pbp output). May span multiple games.
include_transitionboolFalseWhen True, append the _trans/_half split surface plus o_trans_pct/d_trans_pct (213 columns total).
fix_tip_inboolTrueWhen True (default), rim stats count the scrape engine's real "Tip In" vocabulary. When False, reproduce R's literal "Tip-In" test (all_functions.R:2012) — tip-ins silently excluded — for oracle parity.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.

Returns

pl.DataFrame (or pd.DataFrame) with one row per lineup+team — 75 columns (LINEUPS_COLUMNS) or 213 with include_transition=True (LINEUPS_TRANSITION_COLUMNS), rows sorted by p1..p5, team. Empty input yields an empty frame with the documented schema.

col_nametypedescription
p1String
p2String
p3String
p4String
p5String
teamStringTeam-side label or team identifier.
minsFloat64
o_minsFloat64
d_minsFloat64
o_possFloat64
d_possFloat64
ortgFloat64
drtgFloat64
netrtgFloat64
ptsFloat64Points scored.
d_ptsFloat64
fgaFloat64Field goal attempts.
d_fgaFloat64
fgmFloat64Field goals made.
d_fgmFloat64
tpaFloat64
d_tpaFloat64
tpmFloat64
d_tpmFloat64
ftaFloat64Free throw attempts.
d_ftaFloat64
ftmFloat64Free throws made.
d_ftmFloat64
rimaFloat64
d_rimaFloat64
rimmFloat64
d_rimmFloat64
orbFloat64
d_orbFloat64
drbFloat64
d_drbFloat64
blkFloat64Blocks.
d_blkFloat64
toFloat64To.
d_toFloat64
astFloat64Assists.
d_astFloat64
e_possFloat64
fg_pctFloat64Field goal percentage (0-1).
d_fg_pctFloat64
tppFloat64
d_tppFloat64
ftpFloat64
d_ftpFloat64
efg_pctFloat64
d_efg_pctFloat64
ts_pctFloat64True shooting percentage (0-1).
d_ts_pctFloat64
rim_pctFloat64
d_rim_pctFloat64
mid_pctFloat64
d_mid_pctFloat64
tp_rateFloat64
d_tp_rateFloat64
rim_rateFloat64
d_rim_rateFloat64
mid_rateFloat64
d_mid_rateFloat64
ft_rateFloat64Ft rate.
d_ft_rateFloat64
ast_rateFloat64
d_ast_rateFloat64
to_rateFloat64To rate.
d_to_rateFloat64
blk_rateFloat64
o_blk_rateFloat64
orb_pctFloat64Offensive rebound percentage.
drb_pctFloat64Defensive rebound percentage.
time_per_possFloat64
d_time_per_possFloat64

Example

from sportsdataverse.mbb.mbb_ncaa_lineups import ncaa_mbb_lineups
lineups = ncaa_mbb_lineups(pbp)
print(lineups.shape)

# Transition/half-court splits, pandas out

df_pd = ncaa_mbb_lineups(pbp, include_transition=True, return_as_pandas=True)

# Pipeline next step (one line)

lineups.filter(pl.col("mins") > 10).sort("netrtg", descending=True).head()

ncaa_mbb_on_off​

ncaa_mbb_on_off(players: 'Union[str, Sequence[str]]', lineups: 'pl.DataFrame', *, included: 'Union[str, Sequence[str], None]' = None, excluded: 'Union[str, Sequence[str], None]' = None, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'

Team stats for every on/off combination of the given players.

Port of bigballR on_off_generator (all_functions.R:2555-2749, include_transition=F path). For k players, all 2^k on/off assignments are enumerated in R's expand.grid order (first player varies fastest; first row all-On, last all-Off); each combination sums the lineups whose membership matches exactly, re-derives the full ratio block (including e_poss), rounds to 3 decimals, and zeroes NA/Inf. Combinations matching zero lineups produce an all-zero row.

Faithful R quirk (kept, flagged): when included/excluded is passed, the base lineup set comes from the membership filter ONLY — the inferred-team filter is skipped (all_functions.R:2584-2589), so an included player on another team would leak that team's lineups in.

Parameters

ParameterTypeDefaultDescription
playersUnion[str, Sequence[str]]Player name(s) to split on (the Status axis).
lineupsDataFrameLineups frame from ncaa_mbb_lineups.
includedUnion[str, Sequence[str], None]NoneOptional membership filter forwarded to ncaa_mbb_player_lineups (replaces the team filter).
excludedUnion[str, Sequence[str], None]NoneOptional membership filter forwarded to ncaa_mbb_player_lineups (replaces the team filter).
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.

Returns

pl.DataFrame (or pd.DataFrame) with 2^k rows — status (e.g. "A.PLAYER On | B.PLAYER Off") + the 69 stat columns (ON_OFF_COLUMNS).

col_nametypedescription
statusStringStatus label.
minsFloat64
o_minsFloat64
d_minsFloat64
o_possFloat64
d_possFloat64
ortgFloat64
drtgFloat64
netrtgFloat64
ptsFloat64Points scored.
d_ptsFloat64
fgaFloat64Field goal attempts.
d_fgaFloat64
fgmFloat64Field goals made.
d_fgmFloat64
tpaFloat64
d_tpaFloat64
tpmFloat64
d_tpmFloat64
ftaFloat64Free throw attempts.
d_ftaFloat64
ftmFloat64Free throws made.
d_ftmFloat64
rimaFloat64
d_rimaFloat64
rimmFloat64
d_rimmFloat64
orbFloat64
d_orbFloat64
drbFloat64
d_drbFloat64
blkFloat64Blocks.
d_blkFloat64
toFloat64To.
d_toFloat64
astFloat64Assists.
d_astFloat64
e_possFloat64
fg_pctFloat64Field goal percentage (0-1).
d_fg_pctFloat64
tppFloat64
d_tppFloat64
ftpFloat64
d_ftpFloat64
efg_pctFloat64
d_efg_pctFloat64
ts_pctFloat64True shooting percentage (0-1).
d_ts_pctFloat64
rim_pctFloat64
d_rim_pctFloat64
mid_pctFloat64
d_mid_pctFloat64
tp_rateFloat64
d_tp_rateFloat64
rim_rateFloat64
d_rim_rateFloat64
mid_rateFloat64
d_mid_rateFloat64
ft_rateFloat64Ft rate.
d_ft_rateFloat64
ast_rateFloat64
d_ast_rateFloat64
to_rateFloat64To rate.
d_to_rateFloat64
blk_rateFloat64
o_blk_rateFloat64
orb_pctFloat64Offensive rebound percentage.
drb_pctFloat64Defensive rebound percentage.
time_per_possFloat64
d_time_per_possFloat64

Raises

ExceptionDescription
ValueErrorIf the players' team cannot be uniquely inferred from the lineups (R's "ERROR- Player team not found").

Example

from sportsdataverse.mbb.mbb_ncaa_lineups import ncaa_mbb_on_off
split = ncaa_mbb_on_off("KEATON.WAGLER", lineups)
print(split.shape)

# Two-player interaction

duo = ncaa_mbb_on_off(["A.PLAYER", "B.PLAYER"], lineups)

# Pipeline next step (one line)

split.select("status", "netrtg")

ncaa_mbb_player_combos​

ncaa_mbb_player_combos(lineups: 'pl.DataFrame', *, n: 'int' = 2, min_mins: 'float' = 0, included: 'Union[str, Sequence[str], None]' = None, excluded: 'Union[str, Sequence[str], None]' = None, include_transition: 'bool' = False, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'

Team stats for every n-player combination on the court together.

Port of bigballR get_player_combos + team_comb (get_player_combos.R:19-38 + :42-191). Combos are enumerated per team over the byte-sorted unique player pool (lexicographic gtools::combinations order), filtered to combos whose lineups total strictly more than min_mins minutes, then each combo's lineup rows are summed and the ratio block re-derived. Rounding is 2 decimals here (R rounds 3 in get_lineups / on_off_generator) and e_poss is the SUM of the per-lineup estimates, not a recompute — both faithful.

R's include_transition switch is dead code (an exact-match guard at get_player_combos.R:28-30 always forces it back to FALSE); the port implements the suffix-match intent but keeps the False default, which is the only R-reachable behavior.

Parameters

ParameterTypeDefaultDescription
lineupsDataFrameLineups frame from ncaa_mbb_lineups.
nint2Combination size, 1-5.
min_minsfloat0Keep combos with total on-court minutes strictly greater than this (summed over the rounded per-lineup mins).
includedUnion[str, Sequence[str], None]NonePlayer name(s) that must be on the court in every lineup considered.
excludedUnion[str, Sequence[str], None]NonePlayer name(s) that must be off the court in every lineup considered.
include_transitionboolFalseRe-derive the _trans/_half ratio surface (requires a transition lineups frame; forced False otherwise).
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.

Returns

pl.DataFrame (or pd.DataFrame) with one row per combo: team, p1..pn + the stat surface of the input frame. Teams appear in byte-sorted order.

col_nametypedescription
teamStringTeam-side label or team identifier.
p1String
p2String
minsFloat64
o_minsFloat64
d_minsFloat64
o_possFloat64
d_possFloat64
ortgFloat64
drtgFloat64
netrtgFloat64
ptsFloat64Points scored.
d_ptsFloat64
fgaFloat64Field goal attempts.
d_fgaFloat64
fgmFloat64Field goals made.
d_fgmFloat64
tpaFloat64
d_tpaFloat64
tpmFloat64
d_tpmFloat64
ftaFloat64Free throw attempts.
d_ftaFloat64
ftmFloat64Free throws made.
d_ftmFloat64
rimaFloat64
d_rimaFloat64
rimmFloat64
d_rimmFloat64
orbFloat64
d_orbFloat64
drbFloat64
d_drbFloat64
blkFloat64Blocks.
d_blkFloat64
toFloat64To.
d_toFloat64
astFloat64Assists.
d_astFloat64
e_possFloat64
fg_pctFloat64Field goal percentage (0-1).
d_fg_pctFloat64
tppFloat64
d_tppFloat64
ftpFloat64
d_ftpFloat64
efg_pctFloat64
d_efg_pctFloat64
ts_pctFloat64True shooting percentage (0-1).
d_ts_pctFloat64
rim_pctFloat64
d_rim_pctFloat64
mid_pctFloat64
d_mid_pctFloat64
tp_rateFloat64
d_tp_rateFloat64
rim_rateFloat64
d_rim_rateFloat64
mid_rateFloat64
d_mid_rateFloat64
ft_rateFloat64Ft rate.
d_ft_rateFloat64
ast_rateFloat64
d_ast_rateFloat64
to_rateFloat64To rate.
d_to_rateFloat64
blk_rateFloat64
o_blk_rateFloat64
orb_pctFloat64Offensive rebound percentage.
drb_pctFloat64Defensive rebound percentage.
time_per_possFloat64
d_time_per_possFloat64

Raises

ExceptionDescription
ValueErrorIf n is not an integer from 1 to 5.

Example

from sportsdataverse.mbb.mbb_ncaa_lineups import ncaa_mbb_player_combos
duos = ncaa_mbb_player_combos(lineups, n=2, min_mins=5)
print(duos.shape)

# Anchored on one player

trios = ncaa_mbb_player_combos(lineups, n=3, included="KEATON.WAGLER")

# Pipeline next step (one line)

duos.sort("netrtg", descending=True).head()

ncaa_mbb_player_lineups​

ncaa_mbb_player_lineups(lineups: 'pl.DataFrame', *, included: 'Union[str, Sequence[str], None]' = None, excluded: 'Union[str, Sequence[str], None]' = None, return_as_pandas: 'bool' = False) -> 'Union[pl.DataFrame, pd.DataFrame]'

Filter a lineups frame by on-court player membership.

Port of bigballR get_player_lineups (all_functions.R:2761-2792): keep rows where every included player is on the court (in p1..p5) and no excluded player is. With both filters None the input is returned unchanged (R's Included = NA, Excluded = NA passthrough). Membership is tested by name against p1..p5 (R tests the positional first five columns); row order is preserved.

Parameters

ParameterTypeDefaultDescription
lineupsDataFrameLineups frame from ncaa_mbb_lineups (any frame with p1..p5 works).
includedUnion[str, Sequence[str], None]NonePlayer name(s) that must ALL be on the court.
excludedUnion[str, Sequence[str], None]NonePlayer name(s) that must NONE be on the court.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.

Returns

Row-subset of lineups; schema unchanged.

col_nametypedescription
p1String
p2String
p3String
p4String
p5String
teamStringTeam-side label or team identifier.
minsFloat64
o_minsFloat64
d_minsFloat64
o_possFloat64
d_possFloat64
ortgFloat64
drtgFloat64
netrtgFloat64
ptsFloat64Points scored.
d_ptsFloat64
fgaFloat64Field goal attempts.
d_fgaFloat64
fgmFloat64Field goals made.
d_fgmFloat64
tpaFloat64
d_tpaFloat64
tpmFloat64
d_tpmFloat64
ftaFloat64Free throw attempts.
d_ftaFloat64
ftmFloat64Free throws made.
d_ftmFloat64
rimaFloat64
d_rimaFloat64
rimmFloat64
d_rimmFloat64
orbFloat64
d_orbFloat64
drbFloat64
d_drbFloat64
blkFloat64Blocks.
d_blkFloat64
toFloat64To.
d_toFloat64
astFloat64Assists.
d_astFloat64
e_possFloat64
fg_pctFloat64Field goal percentage (0-1).
d_fg_pctFloat64
tppFloat64
d_tppFloat64
ftpFloat64
d_ftpFloat64
efg_pctFloat64
d_efg_pctFloat64
ts_pctFloat64True shooting percentage (0-1).
d_ts_pctFloat64
rim_pctFloat64
d_rim_pctFloat64
mid_pctFloat64
d_mid_pctFloat64
tp_rateFloat64
d_tp_rateFloat64
rim_rateFloat64
d_rim_rateFloat64
mid_rateFloat64
d_mid_rateFloat64
ft_rateFloat64Ft rate.
d_ft_rateFloat64
ast_rateFloat64
d_ast_rateFloat64
to_rateFloat64To rate.
d_to_rateFloat64
blk_rateFloat64
o_blk_rateFloat64
orb_pctFloat64Offensive rebound percentage.
drb_pctFloat64Defensive rebound percentage.
time_per_possFloat64
d_time_per_possFloat64

Example

from sportsdataverse.mbb.mbb_ncaa_lineups import ncaa_mbb_player_lineups
on = ncaa_mbb_player_lineups(lineups, included="KEATON.WAGLER")
print(on.shape)

# Included + excluded combination

df = ncaa_mbb_player_lineups(lineups, included=["A.PLAYER"], excluded=["B.PLAYER"])

# Pipeline next step (one line)

on.select(pl.col("mins").sum())

ncaa_possession_rate_rows​

ncaa_possession_rate_rows(possessions: 'pl.DataFrame', schedule: 'pl.DataFrame', *, league: 'str' = 'mens') -> 'pl.DataFrame'

Map ncaa_{mbb,wbb}_possessions rows onto the team-season-rates possession frame.

Parameters

ParameterTypeDefaultDescription
possessionsDataFrameload_ncaa_mbb_possessions / load_ncaa_wbb_possessions rows.
scheduleDataFrameload_mbb_schedule / load_wbb_schedule rows (game_id, neutral_site), joined on espn_game_id.
leaguestr'mens'"mens" (two 20-minute halves) or "womens" (10-minute quarters from 2016, halves before).

Returns

One row per possession in ~sportsdataverse._common.team_season_rates.RATE_ROWS_SCHEMA, with null four-factor counts.

col_nametypedescription
seasonInt64Season, named by the year it ends.
game_idStringThe stats.ncaa.org contest id.
periodInt64Period of the possession; overtimes follow the last regulation period.
possession_numberInt64Order of the possession in the game.
lateBooleanTrue in the 2nd half (men; women before 2016), the 4th quarter (women from 2016) or an overtime: the periods the clutch window can fall in.
start_clockFloat64Seconds left in the period when the possession starts: its length plus the lengths of the later possessions in the period.
end_clockFloat64Seconds left in the period when the possession ends.
offense_team_idInt64ESPN id of the team with the ball; null for a non-D1 team.
defense_team_idInt64ESPN id of the team on defense; null for a non-D1 team.
offense_is_homeBooleanTrue when the offense is the (nominal) home team; it signs the running score for the clutch margin.
neutral_siteBooleanTrue for an ESPN neutral-site game (False when ESPN does not carry the game); such a game is in neither the home nor the away split.
pointsInt64Points the offense scored on the possession.
fgaFloat64Always null: the NCAA possessions carry no fga counts; the four factors come from the team box (ncaa_team_box_count_rows).
fgmFloat64Always null: the NCAA possessions carry no fgm counts; the four factors come from the team box (ncaa_team_box_count_rows).
fg3mFloat64Always null: the NCAA possessions carry no fg3m counts; the four factors come from the team box (ncaa_team_box_count_rows).
ftaFloat64Always null: the NCAA possessions carry no fta counts; the four factors come from the team box (ncaa_team_box_count_rows).
ftmFloat64Always null: the NCAA possessions carry no ftm counts; the four factors come from the team box (ncaa_team_box_count_rows).
orebFloat64Always null: the NCAA possessions carry no oreb counts; the four factors come from the team box (ncaa_team_box_count_rows).
drebFloat64Always null: the NCAA possessions carry no dreb counts; the four factors come from the team box (ncaa_team_box_count_rows).
tovFloat64Always null: the NCAA possessions carry no tov counts; the four factors come from the team box (ncaa_team_box_count_rows).
ff_possFloat64Always null: the turnover rate's denominator comes from the team box.

Raises

ExceptionDescription
ValueErrorIf league is not "mens" or "womens".

Example

from sportsdataverse.mbb.mbb_loaders import load_mbb_schedule, load_ncaa_mbb_possessions
from sportsdataverse.mbb.mbb_team_season_rates import ncaa_possession_rate_rows
rows = ncaa_possession_rate_rows(load_ncaa_mbb_possessions(2025), load_mbb_schedule(2025))

ncaa_score_rows​

ncaa_score_rows(pbp: 'pl.DataFrame', schedule: 'pl.DataFrame', *, league: 'str' = 'mens') -> 'pl.DataFrame'

Map the stats.ncaa.org play-by-play onto the game-flow score rows.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameload_ncaa_mbb_pbp / load_ncaa_wbb_pbp rows, in release (game) order (contest_id, season, period, game_seconds, home_score, away_score, event_team_espn_team_id, home_espn_team_id, away_espn_team_id, espn_game_id).
scheduleDataFrameload_mbb_schedule / load_wbb_schedule rows (game_id, neutral_site), joined on espn_game_id; a contest it lacks is not neutral.
leaguestr'mens'"mens" or "womens".

Returns

Rows in ~sportsdataverse._common.game_flow.SCORE_ROWS_SCHEMA, without home_wp.

col_nametypedescription
seasonInt64Season, named by the year it ends (the WNBA season is its calendar year).
game_idStringstats.ncaa.org contest id.
orderInt64The play's position in its game (the pbp order_index, or the release row order for college).
home_team_idInt64The home team's id (stats.nba.com, or the ESPN team id for college; null for a non-D1 host).
away_team_idInt64The away team's id (stats.nba.com, or the ESPN team id for college; null for a non-D1 visitor).
neutral_siteBooleanTrue for a neutral-site game (no home-court prior); always False in the NBA / WNBA stats schedule, which carries no venue.
elapsedFloat64Game-clock seconds run when the play happens, counted from the tip.
sec_leftFloat64The win-probability clock: seconds left in regulation, or in the overtime period.
game_secondsFloat64Game length in seconds: regulation plus the overtimes played.
event_team_idInt64The play's team (the model's ball side); 0 or null for a team-less play.
home_scoreInt64Home running score after the play.
away_scoreInt64Away running score after the play.

Raises

ExceptionDescription
ValueErrorIf league is not "mens" or "womens".

Example

from sportsdataverse.mbb.mbb_loaders import load_mbb_schedule, load_ncaa_mbb_pbp
from sportsdataverse.mbb.mbb_game_flow import ncaa_score_rows
rows = ncaa_score_rows(load_ncaa_mbb_pbp(2026), load_mbb_schedule(2026))

ncaa_situation_rows​

ncaa_situation_rows(possessions: 'pl.DataFrame', schedule: 'pl.DataFrame', *, league: 'str' = 'mens') -> 'pl.DataFrame'

Map ncaa_{mbb,wbb}_possessions rows onto the situational-splits possession frame.

Parameters

ParameterTypeDefaultDescription
possessionsDataFrameload_ncaa_mbb_possessions / load_ncaa_wbb_possessions rows.
scheduleDataFrameload_mbb_schedule / load_wbb_schedule rows (game_id, neutral_site).
leaguestr'mens'"mens" or "womens".

Returns

One row per possession in ~sportsdataverse._common.situational_splits.situation_row_schema (String player ids, null is_second_chance).

col_nametypedescription
seasonInt64Season, named by the year it ends.
game_idStringThe stats.ncaa.org contest id.
periodInt64Period of the possession; overtimes follow the last regulation period.
possession_numberInt64Order of the possession in the game.
lateBooleanTrue in the 2nd half (men; women before 2016), the 4th quarter (women from 2016) or an overtime: the periods the clutch window can fall in.
start_clockFloat64Seconds left in the period when the possession starts: its length plus the lengths of the later possessions in the period.
end_clockFloat64Seconds left in the period when the possession ends.
offense_team_idInt64ESPN id of the team with the ball; null for a non-D1 team.
defense_team_idInt64ESPN id of the team on defense; null for a non-D1 team.
offense_is_homeBooleanTrue when the offense is the (nominal) home team; it signs the running score for the clutch margin.
neutral_siteBooleanTrue for an ESPN neutral-site game (False when ESPN does not carry the game); such a game is in neither the home nor the away split.
pointsInt64Points the offense scored on the possession.
fgaFloat64Always null: the NCAA possessions carry no fga counts; the four factors come from the team box (ncaa_team_box_count_rows).
fgmFloat64Always null: the NCAA possessions carry no fgm counts; the four factors come from the team box (ncaa_team_box_count_rows).
fg3mFloat64Always null: the NCAA possessions carry no fg3m counts; the four factors come from the team box (ncaa_team_box_count_rows).
ftaFloat64Always null: the NCAA possessions carry no fta counts; the four factors come from the team box (ncaa_team_box_count_rows).
ftmFloat64Always null: the NCAA possessions carry no ftm counts; the four factors come from the team box (ncaa_team_box_count_rows).
orebFloat64Always null: the NCAA possessions carry no oreb counts; the four factors come from the team box (ncaa_team_box_count_rows).
drebFloat64Always null: the NCAA possessions carry no dreb counts; the four factors come from the team box (ncaa_team_box_count_rows).
tovFloat64Always null: the NCAA possessions carry no tov counts; the four factors come from the team box (ncaa_team_box_count_rows).
ff_possFloat64Always null: the turnover rate's denominator comes from the team box.
reg_periodsInt64Regulation periods of the game: 4 quarters, or 2 halves.
is_transitionBooleanThe possession is transition (BB-D7's flag for the pros, the release's own for college).
is_garbage_timeBooleanThe possession is in garbage time (bigballR's rule; BB-D7 for the pros, the release's flag for college).
is_second_chanceBooleanThe possession had an offensive rebound; null in college (the NCAA possessions carry no rebound counts).
off_1StringOffense player 1 on the floor as the possession starts.
off_2StringOffense player 2 on the floor as the possession starts.
off_3StringOffense player 3 on the floor as the possession starts.
off_4StringOffense player 4 on the floor as the possession starts.
off_5StringOffense player 5 on the floor as the possession starts.
def_1StringDefense player 1 on the floor as the possession starts.
def_2StringDefense player 2 on the floor as the possession starts.
def_3StringDefense player 3 on the floor as the possession starts.
def_4StringDefense player 4 on the floor as the possession starts.
def_5StringDefense player 5 on the floor as the possession starts.

Raises

ExceptionDescription
ValueErrorIf league is not "mens" or "womens".

Example

from sportsdataverse.mbb.mbb_loaders import load_mbb_schedule, load_ncaa_mbb_possessions
from sportsdataverse.mbb.mbb_situational import ncaa_situation_rows
rows = ncaa_situation_rows(load_ncaa_mbb_possessions(2025), load_mbb_schedule(2025))

ncaa_stint_rows​

ncaa_stint_rows(pbp: 'pl.DataFrame', possessions: 'pl.DataFrame', *, league: 'str' = 'mens') -> 'pl.DataFrame'

Map the stats.ncaa.org pbp and possessions onto the stint-row frame.

One row per event in game order, on the event's lineup: its clock, its points (a free throw's on the row of the game's last foul) and the possessions that start at it. A possession starts at the first event of its poss_num; one whose poss_team is neither side is dropped.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameload_ncaa_mbb_pbp / load_ncaa_wbb_pbp rows, in release (game) order, with period, game_seconds and poss_num.
possessionsDataFrameload_ncaa_mbb_possessions / load_ncaa_wbb_possessions rows (contest_id, poss_num, poss_team, home, away).
leaguestr'mens'"mens" (20-minute halves) or "womens" (10-minute quarters from 2016, halves before); overtimes are 5 minutes.

Returns

Rows in sportsdataverse._common.game_stints.stint_row_schema with String player ids: period, clock (seconds left in the period after the event), order (the event's row in the release) and is_garbage_time (the event's own flag).

col_nametypedescription
seasonInt64Season of the action.
game_idStringstats.ncaa.org contest id.
home_team_idInt64Home ESPN team id (null for a non-D1 team).
away_team_idInt64Away ESPN team id (null for a non-D1 team).
home_1StringHome player 1 on the floor.
home_2StringHome player 2 on the floor.
home_3StringHome player 3 on the floor.
home_4StringHome player 4 on the floor.
home_5StringHome player 5 on the floor.
away_1StringAway player 1 on the floor.
away_2StringAway player 2 on the floor.
away_3StringAway player 3 on the floor.
away_4StringAway player 4 on the floor.
away_5StringAway player 5 on the floor.
secondsFloat64Game clock that ran into this action (from the previous action of the period).
home_ptsInt64Points the home team scored on this action; a free throw's points sit on the row of the game's last foul.
away_ptsInt64Points the away team scored on this action; a free throw's points sit on the row of the game's last foul.
home_possInt64Possessions of the home team that start at this action.
away_possInt64Possessions of the away team that start at this action.
periodInt64Period of the action.
clockFloat64Period clock (seconds left) after the event; 0 on the period's last event, which takes the period's tail.
orderInt64The event's row in the pbp release (its place in the game).
is_garbage_timeBooleanWhether the event is in garbage time: the release's own is_garbage_time (bigballR's rule).

Raises

ExceptionDescription
ValueErrorIf league is not "mens" or "womens".

Example

from sportsdataverse.mbb.mbb_loaders import load_ncaa_mbb_pbp, load_ncaa_mbb_possessions
from sportsdataverse.mbb.mbb_game_stints import ncaa_stint_rows
rows = ncaa_stint_rows(load_ncaa_mbb_pbp(2025), load_ncaa_mbb_possessions(2025))

ncaa_team_box_count_rows​

ncaa_team_box_count_rows(team_box: 'pl.DataFrame') -> 'pl.DataFrame'

Map ncaa_{mbb,wbb}_team_box rows onto the four-factor count frame.

Each row is one team's offense in one game: its FGA, FGM, 3PM, FTA, FTM, offensive rebounds and turnovers, the opponent's defensive rebounds (d_drb) and its own possessions (o_poss). offense_is_home is the box's own home designation (team == home).

Parameters

ParameterTypeDefaultDescription
team_boxDataFrameload_ncaa_mbb_team_box / load_ncaa_wbb_team_box rows.

Returns

One row per (game, team) in ~sportsdataverse._common.team_season_rates.COUNT_ROWS_SCHEMA.

col_nametypedescription
seasonInt64Season, named by the year it ends (2025 is 2024-25).
game_idStringThe stats.ncaa.org contest id.
offense_team_idInt64ESPN id of the team whose offense the row counts; null for a non-D1 team.
defense_team_idInt64ESPN id of its opponent; null for a non-D1 team.
offense_is_homeBooleanTrue when the team is the game's (nominal) home team in the NCAA team box; a neutral-site game is in neither split.
fgaFloat64Field-goal attempts in the game.
fgmFloat64Field goals made in the game.
fg3mFloat64Three-pointers made in the game.
ftaFloat64Free-throw attempts in the game.
ftmFloat64Free throws made in the game.
orebFloat64Offensive rebounds in the game.
drebFloat64The opponent's defensive rebounds in the game (the other half of the offensive-rebound chances).
tovFloat64Turnovers in the game.
ff_possFloat64The team box's offensive possessions in the game, the turnover-rate denominator.

Example

from sportsdataverse.mbb.mbb_loaders import load_ncaa_mbb_team_box
from sportsdataverse.mbb.mbb_team_season_rates import ncaa_team_box_count_rows
counts = ncaa_team_box_count_rows(load_ncaa_mbb_team_box(2025))

ncaa_team_coaches​

ncaa_team_coaches(root: 'str | Path', seasons: 'int | list[int]', *, league: 'str' = 'mens') -> 'pl.DataFrame'

Every team-season's head coach from a raw-repo tree of stats.ncaa.org roster pages.

Parameters

ParameterTypeDefaultDescription
rootstr | PathThe ncaa-mbb-hoops-raw / ncaa-wbb-hoops-raw checkout.
seasonsint | list[int]A season or list of seasons, named by the year it ends.
leaguestr'mens'"mens" or "womens".

Returns

One row per page with a coach card, in NCAA_COACHES_SCHEMA; team_id is the ESPN team id from the season's teams/json crosswalk (null when it has none). A season with no crosswalk file is skipped with a warning.

col_nametypedescription
seasonInt64Season, named by the year it ends (2025 is 2024-25).
ncaa_team_idInt64stats.ncaa.org team-season id (the roster page's file name, teams/{id}).
team_idInt64ESPN team id of the school, from the season's teams/json crosswalk; null when the crosswalk has none.
teamStringSchool name as stats.ncaa.org's crosswalk gives it.
coach_idInt64NCAA person id of the head coach (stats.ncaa.org /people/{id}).
coachStringHead coach's name on the page's Coach card.
career_seasonsInt64The coach's seasons as a head coach through this one, every school and division (the card's Seasons).
career_winsInt64The coach's career wins through this season (the card's Record; the NCAA drops vacated wins).
career_lossesInt64The coach's career losses through this season (the card's Record).

Raises

ExceptionDescription
ValueErrorIf league is not "mens" or "womens".

ncaa_team_game_counts​

ncaa_team_game_counts(pbp: 'pl.DataFrame') -> 'pl.DataFrame'

Each team's shots, free throws, rebounds and turnovers per game, whole and with garbage time split out.

Sums the stats.ncaa.org events by the team that made them (event_team_espn_team_id): a field goal is a shot_value 2 or 3 event, a free throw a shot_value 1 event, made when event_result is made; oreb / dreb / tov count the Offensive Rebound / Defensive Rebound / Turnover events (team rebounds and team turnovers included, Deadball Rebound not). The garbage split is each event's own is_garbage_time (bigballR's flag, the one the possessions release carries); an event with no flag is in all only.

Parameters

ParameterTypeDefaultDescription
pbpDataFrameload_ncaa_mbb_pbp / load_ncaa_wbb_pbp rows.

Returns

One row per (season, game_id, team_id, family, split): family all (split all) and family garbage (garbage_time, not_garbage_time, a split with no event of the team has no row), with game_id the stats.ncaa.org contest id (Utf8), team_id the ESPN team id (Int64; an event of a team without one, a non-D1 side, is dropped) and the COUNT_COLUMNS (Int64). Within a game the two garbage rows add up to the all row when every event is flagged. An empty input returns that schema with zero rows.

col_nametypedescription
seasonInt64Season year (the year the season ends).
game_idStringThe stats.ncaa.org contest id.
team_idInt64ESPN team id of the team that made the events; events of a side with no ESPN id (non-D1) are dropped.
familyStringall (the whole game) or garbage.
splitStringall, or garbage_time / not_garbage_time by each event's is_garbage_time.
fgaInt64Field-goal attempts in the split: the team's shot_value 2 and 3 events in the ncaa pbp.
fgmInt64Made field goals in the split (event_result made).
fg3aInt64Three-point attempts in the split (shot_value 3).
fg3mInt64Made threes in the split.
ftaInt64Free-throw attempts in the split (shot_value 1).
ftmInt64Made free throws in the split.
orebInt64Offensive rebounds in the split (Offensive Rebound events, team rebounds included).
drebInt64Defensive rebounds in the split (Defensive Rebound events, team rebounds included).
tovInt64Turnovers in the split (Turnover events, team turnovers included).

Raises

ExceptionDescription
KeyErrorIf pbp is missing a column it reads.

Example

from sportsdataverse.mbb.mbb_loaders import load_ncaa_mbb_pbp
from sportsdataverse.mbb.mbb_situational import ncaa_team_game_counts
ncaa_team_game_counts(load_ncaa_mbb_pbp(2026)).filter(split="not_garbage_time").head()

order_lineup​

order_lineup(player_codes_and_ids: 'list[dict[str, str]]', players_by_id: 'dict[str, dict[str, Any]]', team_season: 'str') -> 'list[dict[str, str]]'

Order a 5-man lineup X1_X2_X3_X4_X5 into PG/SG/SF/PF/C slot order.

Faithful port of PositionUtils.orderLineup (PositionUtils.ts:696-761). Greedily fits each player (in input order) to their best-scoring slot via _fit_player (dominated by pos_class_to_score on the player's posClass, tie-broken by their raw posConfidences), evicting and recursively re-fitting any player displaced along the way, then applies apply_relative_positional_overrides (keyed on team_season) as a final hand-tuned correction pass.

Parameters

ParameterTypeDefaultDescription
player_codes_and_idslist[dict[str, str]]The lineup membership, each a {"code": ..., "id": ...} dict. Order does not affect the final result (the slot-fitting algorithm is order-invariant by construction -- displaced players are always re-fit).
players_by_iddict[str, dict[str, Any]]Per-player positional info keyed by id, each a {"posConfidences": [pg, sg, sf, pf, c], "posClass": "..."} dict (the tradPosList-ordered raw confidence scores plus the classifier's ID_TO_POSITION-keyed class label).
team_seasonstrKey into RELATIVE_POSITION_FIXES for the final override pass.

Returns

A 5-element list of {"code": ..., "id": ...} dicts in PG/SG/SF/PF/C order.

Example

::

from sportsdataverse.mbb.mbb_positions import order_lineup
players_by_id = {
"Cowan, Anthony": {"posConfidences": [60, 40, 10, 0, 0], "posClass": "s-PG"},
"Ayala, Eric": {"posConfidences": [40, 60, 10, 0, 0], "posClass": "CG"},
}
order_lineup(
[{"code": "AnCowan", "id": "Cowan, Anthony"},
{"code": "ErAyala", "id": "Ayala, Eric"}],
players_by_id, "",
)

pos_class_to_score​

pos_class_to_score(pos_class: 'str') -> 'int'

Ordinal "positional weight" for a position class, PG=1000..C=8000.

Faithful port of PositionUtils.posClassToScore (PositionUtils.ts:629-654, a literal switch). Unmapped classes default to 4000 (the TS default-case comment notes "won't happen").

Parameters

ParameterTypeDefaultDescription
pos_classstrA position-class code (e.g. "PG", "WF", "C").

Returns

The class's ordinal score.

Example

::

from sportsdataverse.mbb.mbb_positions import pos_class_to_score
pos_class_to_score("WF")

project_bracket​

project_bracket(resume: 'pl.DataFrame', auto_bids: 'set[str]', *, league: 'str' = 'mens', field_size: 'int' = 68) -> 'pl.DataFrame'

Select and seed a tournament field from a per-team résumé frame.

Parameters

ParameterTypeDefaultDescription
resumeDataFrameOne row per (season, team_id) with adj_em_z, sos, wab, quad1_w (the ratings + strength-of-schedule outputs joined).
auto_bidsset[str]team_id set of conference auto-bid teams (see ~sportsdataverse.mbb.mbb_college_season.conference_auto_bids); always in the field.
leaguestr'mens'"mens" or "womens" (kept for shim parity; the blend is league-agnostic).
field_sizeint68Tournament field size (68).

Returns

One row per input team: season, team_id, resume_score, projected_seed (1-16, null outside the field; in a 68-team field the last four at-large teams and the four worst auto-bids share First Four slots, so every line has four slots), at_large_prob (logistic in resume_score centred on the selection cutoff -- every selected at-large clears 0.5), auto_bid, at_large_rank (1 = the best résumé without an auto-bid; null for auto-bids), bid (exactly field_size true).

No returns table is published for this function: no capture: it needs a resume frame (strength of schedule joined with the ratings' adj_em_z) that no package function returns.

Example

from sportsdataverse.mbb.mbb_bracketology import project_bracket
field = project_bracket(resume, auto_bids)

regress_shot_quality​

regress_shot_quality(stat: 'float', pos: 'int', feat: 'str', player: 'dict[str, Any]') -> 'float'

Shrink a small-sample shot-quality stat toward its positional average.

Faithful port of PositionUtils.regressShotQuality (PositionUtils.ts:216-258). Only the three relative shot-quality features (calc_three_relative / calc_rim_relative / calc_mid_relative) are regressed; any other feat passes stat through unchanged. A player is regressed toward the positional average whenever the relevant shot volume is below max(0.25 * total_fga, 15) (i.e. under 25% of their attempts come from that zone, floored at 15 attempts). A center (pos == 4) who took 0-2 threes and made none is left at 0 to avoid widespread changes.

Parameters

ParameterTypeDefaultDescription
statfloatThe raw (unregressed) feature value.
posintPosition index (0=pg ... 4=c).
featstrFeature field name (only the three relative shot-quality keys trigger regression; anything else is a passthrough).
playerdict[str, Any]The player stat dict; reads total_off_fga and the per-feature volume field (total_off_{3p,2pmid,2prim}_attempts), each shaped {"value": N}.

Returns

The regressed feature value (or stat unchanged when the feature is not regressed, volume is sufficient, or the center-3s carve-out fires).

Raises

ExceptionDescription
KeyErrorIf player lacks total_off_fga (faithful to the TS, which throws on the same missing field).

Example

from sportsdataverse.mbb.mbb_positions import regress_shot_quality
player = {"total_off_fga": {"value": 25},
"total_off_3p_attempts": {"value": 1}}
regress_shot_quality(-15.5, 2, "misc_feature", player)

# Low-volume shrink toward the positional average

regress_shot_quality(100, 3, "calc_rim_relative",
{"total_off_fga": {"value": 25},
"total_off_2prim_attempts": {"value": 8}})

strength_of_schedule​

strength_of_schedule(results: 'pl.DataFrame', ratings: 'pl.DataFrame', *, league: 'str' = 'mens') -> 'pl.DataFrame'

Per-team SoS + Quad 1-4 record + WAB from completed games and ratings.

Parameters

ParameterTypeDefaultDescription
resultsDataFrameCompleted games with game_id, season, home_team_id, away_team_id, home_score, away_score, neutral_site.
ratingsDataFrameOne row per team with season, team_id, adj_em, rank (the mbb_team_ratings output). Team-id dtype must match results.
leaguestr'mens'"mens" or "womens" (quad thresholds, HFA, bubble EM).

Returns

One row per (season, team_id): season, team_id, sos, sos_rank, wab, quad1_w .. quad4_l, quality_wins. sos is the mean opponent adj_em (rank 1 = hardest schedule); quads follow the NET venue-adjusted opponent-rank thresholds; quality_wins is Quad-1 + Quad-2 wins; wab is actual wins minus a bubble-quality team's expected wins against the same schedule. Empty input returns the schema with zero rows.

No returns table is published for this function: no capture: it needs a schedule with home_team_id / away_team_id columns, and no package function returns one (load_mbb_schedule ships home_id / away_id).

Raises

ExceptionDescription
ValueErrorIf the team-id dtypes of results and ratings disagree.

Example

from sportsdataverse.mbb.mbb_strength_of_schedule import strength_of_schedule
resume = strength_of_schedule(results, ratings)

test_positional_aware_filter​

test_positional_aware_filter(sorted_to_test: 'list[dict[str, str]]', pve_frags: 'list[dict[str, Any]]', nve_frags: 'list[dict[str, Any]]') -> 'bool'

Check a positional-aware filter (from build_positional_aware_filter)

against a sorted (order_lineup-ordered) lineup array.

Faithful port of PositionUtils.testPositionalAwareFilter (PositionUtils.ts:831-858). A fragment matches if any of its position-restricted slots (or, when pos is empty, any slot at all) has a code/id containing the fragment's filter text (case-insensitive substring match). Every positive fragment must match (vacuously true if there are none); no negative fragment may match (vacuously true if there are none).

Parameters

ParameterTypeDefaultDescription
sorted_to_testlist[dict[str, str]]The ordered lineup, each a {"id": ..., "code": ...} dict (as returned by order_lineup).
pve_fragslist[dict[str, Any]]Positive-filter fragments (must ALL match).
nve_fragslist[dict[str, Any]]Negative-filter fragments (NONE may match).

Returns

Whether the lineup satisfies both the positive and negative filters.

Example

::

from sportsdataverse.mbb.mbb_positions import test_positional_aware_filter
lineup = [{"code": "AnCowan", "id": "Cowan, Anthony"}]
test_positional_aware_filter(lineup, [{"filter": "cowan", "pos": []}], [])

using_roster_pos​

using_roster_pos(pos_class: 'str', roster_pos: 'str | None') -> 'tuple[str, str | None]'

Reconcile a stats-derived position class against roster metadata.

Faithful port of PositionUtils.usingRosterPos (PositionUtils.ts:583-626). When the classifier landed on an "unsure" bucket ("G?"/"F/C?"), roster info narrows it (a roster "C" always wins outright); otherwise an obviously-wrong stats classification is compromised toward the roster-implied side, gated by pos_class_to_score thresholds.

Parameters

ParameterTypeDefaultDescription
pos_classstrThe stats-derived position class.
roster_posstr | NoneThe roster-reported position ("G"/"F"/"C"), or None/"" when unknown. if (rosterPos) (ts:587) is a plain JS truthiness check on a string -- "" and None behave identically (both mean "no correction"), so if not roster_pos is the faithful Python mirror, not an is None landmine.

Returns

A (position, info) tuple. info is None when no correction/explanation applies (matches the TS undefined), else a human-readable note on why the position was adjusted.

Example

from sportsdataverse.mbb.mbb_positions import using_roster_pos
using_roster_pos("G?", "C")

weighted_avg​

weighted_avg(mutable_acc: 'LineupStatSet', obj: 'LineupStatSet') -> 'None'

Merge obj into mutable_acc with possession weighting.

Faithful port of LineupUtils.weightedAvg (LineupUtils.ts:645). Mutates mutable_acc in place (matching the upstream mutable-state contract) and returns None. Each call accumulates a weighted sum, not a weighted average -- the companion completeWeightedAvg (upstream LineupUtils.ts:752, not yet ported) divides by the accumulated weight totals to finish the average. The per-field weight used at each merge step is derived from obj's own totals (e.g. that single lineup's total_off_fga), not from any running total on mutable_acc -- callers accumulating many lineups must call weighted_avg once per lineup so every lineup contributes its own weight.

Parameters

ParameterTypeDefaultDescription
mutable_accLineupStatSetThe running accumulator (LineupStatSet). Mutated in place; fields absent from the accumulator are initialized to {"value": 0.0} (plus old_value / override when obj's field carries a luck-adjustment override marker) before obj's contribution is added.
objLineupStatSetThe per-lineup LineupStatSet document to merge in.

Returns

None. mutable_acc is mutated in place.

Raises

ExceptionDescription
NotImplementedErrorIf obj carries a game_info key -- that merge branch is deliberately deferred (see module docstring).

Example

from sportsdataverse.mbb.mbb_lineup_stats import weighted_avg

acc: dict = {}
weighted_avg(acc, lineup_a)
weighted_avg(acc, lineup_b)
print(acc["off_poss"]["value"]) # plain sum (SUM_FIELDS)

# Two-lineup possession-weighted merge

acc = {}
for lineup in three_lineups:
weighted_avg(acc, lineup)
# acc now holds weighted SUMS; complete_weighted_avg (not yet
# ported) is required to turn these into rate-stat averages.