Skip to main content

College baseball — additional Python functions

Hand-written wrappers, loaders, and helpers in sportsdataverse.baseball.college_baseball that are not generated API-endpoint wrappers (those have their own reference pages).

ESPN​

espn_college_baseball_player_box​

espn_college_baseball_player_box(game_id: 'int | str', return_as_pandas: 'bool' = False, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame'

Pull one college baseball game's player box score from ESPN's summary endpoint.

The baseballr table of the same name (baseballr::espn_college_baseball_player_box): one row per athlete and side, batters then pitchers for the first team listed, then the second. One request.

Parameters

ParameterTypeDefaultDescription
game_idint | strESPN game (event) id, from espn_college_baseball_scoreboard.
return_as_pandasboolFalseReturn a pandas frame instead of polars (pyarrow-backed columns, so the nullable ids stay integers).

Returns

The columns of sportsdataverse.mlb.espn_mlb_player_box. A zero-row frame with those columns when ESPN lists no athletes for the game, as it does for many smaller games (baseballr returns NULL there).

col_nametypedescription
game_idInt64ESPN game (event) id.
seasonInt32Season (four-digit year) of the game, from the summary header.
season_typeInt32ESPN season type of the game: 1 preseason, 2 regular season, 3 postseason (MLB); ESPN files the college postseason under other types (the 2024 Men's College World Series final is 6).
game_dateDateUS/Eastern calendar date of the scheduled first pitch.
game_date_timeDatetimeScheduled first pitch, US/Eastern.
stat_groupStringWhich side of the box score the row reports: batting or pitching. A two-way player has one row for each.
team_idInt64ESPN team id of the athlete's team.
team_nameStringTeam nickname, e.g. Cardinals.
team_abbreviationStringTeam abbreviation, e.g. STL.
team_display_nameStringFull team name, e.g. St. Louis Cardinals.
athlete_idInt64ESPN athlete id of the player the row reports.
athlete_display_nameStringAthlete's full name.
athlete_short_nameStringAthlete's short name, e.g. N. Arenado.
athlete_position_nameStringPosition the athlete played in the game, e.g. Third Base or Pitcher.
athlete_position_abbreviationStringAbbreviation of the position the athlete played, e.g. 3B or P.
starterBooleanTrue when the athlete started the game (on the batting side, was in the starting lineup).
bat_orderInt32Spot in the batting order, 1-9; a substitute takes the spot of the player he replaced. Null on pitching rows.
activeBooleanESPN's active flag for the athlete's box-score entry.
h_abStringBatting: hits and at-bats as text, e.g. 2-4.
abStringBatting: at-bats.
rStringRuns: scored by the batter on a batting row, allowed by the pitcher on a pitching row.
hStringHits: by the batter on a batting row, allowed by the pitcher on a pitching row.
rbiStringBatting: runs batted in.
hrStringHome runs: hit by the batter on a batting row, allowed by the pitcher on a pitching row.
bbStringWalks: drawn by the batter on a batting row, issued by the pitcher on a pitching row.
kStringStrikeouts: by the batter on a batting row, by the pitcher on a pitching row.
number_pStringBatting: pitches the batter saw (ESPN's #P).
avgStringBatting: the batter's season batting average through the game, ESPN's display text (e.g. .286).
obpStringBatting: the batter's season on-base percentage through the game.
slgStringBatting: the batter's season slugging percentage through the game.
ipStringPitching: innings pitched, in ESPN's thirds notation (6.1 = six and one third).
erStringPitching: earned runs allowed.
pc_stStringPitching: pitches and strikes thrown, e.g. 95-58.
eraStringPitching: the pitcher's season ERA through the game.
pcStringPitching: pitches thrown.

Raises

ExceptionDescription
NoDataErrorESPN answered 404 for the game.
AssetFetchErrorThe request failed (a non-2xx answer or a connection failure after retries).

Example

from sportsdataverse.baseball.college_baseball import espn_college_baseball_player_box
player_box = espn_college_baseball_player_box(game_id=401675653)
print(player_box.shape)

# Pipeline next step (one line)

import polars as pl
player_box.filter(pl.col("stat_group") == "batting").select("athlete_display_name", "h_ab", "rbi")

espn_college_baseball_team_box​

espn_college_baseball_team_box(game_id: 'int | str', return_as_pandas: 'bool' = False, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame'

Pull one college baseball game's team box score from ESPN's summary endpoint.

The baseballr table of the same name (baseballr::espn_college_baseball_team_box): one row per team with the game header, the team's identity, every batting, pitching and fielding stat ESPN reports for the game, and the opponent's identity and score. One request.

Parameters

ParameterTypeDefaultDescription
game_idint | strESPN game (event) id, from espn_college_baseball_scoreboard.
return_as_pandasboolFalseReturn a pandas frame instead of polars (pyarrow-backed columns, so the nullable ids stay integers).

Returns

Two rows, one per team, with the columns of sportsdataverse.mlb.espn_mlb_team_box. ESPN's college box carries fewer stats (about 70 batting_* / pitching_* / fielding_* columns) and none at all for many smaller games, which then have only the identity, score and opponent columns. A zero-row frame with the documented columns when ESPN has no box score for the game.

col_nametypedescription
game_idInt64ESPN game (event) id.
seasonInt32Season (four-digit year) of the game, from the summary header.
season_typeInt32ESPN season type of the game: 1 preseason, 2 regular season, 3 postseason (MLB); ESPN files the college postseason under other types (the 2024 Men's College World Series final is 6).
game_dateDateUS/Eastern calendar date of the scheduled first pitch.
game_date_timeDatetimeScheduled first pitch, US/Eastern.
team_idInt64ESPN team id of the team the row reports.
team_uidStringESPN universal team id (UID), e.g. s:1l:10t:24.
team_slugStringURL slug of the team, e.g. st-louis-cardinals.
team_locationStringTeam city or school, e.g. St. Louis.
team_nameStringTeam nickname, e.g. Cardinals.
team_abbreviationStringTeam abbreviation, e.g. STL.
team_display_nameStringFull team name, e.g. St. Louis Cardinals.
team_short_display_nameStringShort team name, e.g. Cardinals.
team_colorStringTeam primary color, hex without the leading #.
team_alternate_colorStringTeam alternate color, hex without the leading #.
team_logoStringURL of the team logo.
batting_hit_by_pitchStringTeam batting: Hit By Pitch (HBP). The number of times a player has been by a pitch. ESPN's display text.
batting_strikeoutsStringTeam batting: Strikeouts (SO). The number of times a player strikes out. ESPN's display text.
batting_rb_isStringTeam batting: Runs Batted In (RBI). The number of runs scored by a batter's play. ESPN's display text.
batting_sac_hitsStringTeam batting: Sacrifice Hit (SH). The number of sacrifice bunts that allow baserunners to advance. ESPN's display text.
batting_hitsStringTeam batting: Hits (H). The number of hits. ESPN's display text.
batting_stolen_basesStringTeam batting: Stolen Bases (SB). The number of bases stolen. ESPN's display text.
batting_walksStringTeam batting: Walks (BB). The number of times a batter reaches base on four balls. ESPN's display text.
batting_runsStringTeam batting: Runs (R). The number of runs scored. ESPN's display text.
batting_gid_psStringTeam batting: Ground Into Double Play (GIDP). The number of times a batter grounds into a double play. ESPN's display text.
batting_sac_fliesStringTeam batting: Sacrifice Flies (SF). The number of fly outs on which a runner scored (a sacrifice fly). ESPN's display text.
batting_at_batsStringTeam batting: At Bats (AB). The number of times a batter comes up to bat not counting walks and sacrifices. ESPN's display text.
batting_home_runsStringTeam batting: Home Runs (HR). The number of hits that allowed the batter to round the bases and score without the aid of an error of the defense. ESPN's display text.
batting_grand_slam_home_runsStringTeam batting: Grand Slam Home Runs (GSHR). The number of hits that allowed the batter and 3 of his teammates to round the bases and score without the aid of an error of the defense. ESPN's display text.
batting_runners_left_on_baseStringTeam batting: Runners Left On Base (LOB). The number runners remain on base after the batter makes an out at the plate. ESPN's display text.
batting_triplesStringTeam batting: Triples (3B). The number of hits that result in the batter reaching 3rd base without the aid of an error. ESPN's display text.
batting_doublesStringTeam batting: Doubles (2B). The number of times that a batter reaches second base as the result of a hit without an error being committed. ESPN's display text.
batting_caught_stealingStringTeam batting: Caught Stealing (CS). The number of times that a baserunner attempts to steal a base but is thrown out. ESPN's display text.
batting_pitchesStringTeam batting: Pitches (P). The number of pitches faced. ESPN's display text.
batting_total_basesStringTeam batting: Total Bases (TB). The number of bases calculated as 1 for a 1B, 2 for a 2B, 3 for a 3B and 4 for a HR. ESPN's display text.
batting_extra_base_hitsStringTeam batting: Extra Base Hits (XBH). The number of hits that are greater than singles. ESPN's display text.
batting_avgStringTeam batting: Batting Average (AVG). The average number of times the batter reached successfully on base due to a hit: hits / atBats. ESPN's display text.
batting_slug_avgStringTeam batting: Slugging Percentage (SLG). Slugging percentage is a metric that is meant to measuring how many bases the hitter safely advances to after making contact with the ball: (totalBases / atBats). ESPN's display text.
batting_on_base_pctStringTeam batting: On Base Percentage (OBP): (hits + walks + hit by pitch) / (at bats + walks + hit by pitch + sacrifice flies). ESPN's display text.
batting_bipaStringTeam batting: Balls In Play Average (BIPA). The average of a batter when the ball is put in play or batting average without factoring at bats that result in a home run or a strikeout. ESPN's display text.
batting_mlb_ratingStringTeam batting: MLB Rating (MLB). The MLB rating. ESPN's display text.
pitching_savesStringTeam pitching: Saves (SV). The number of times a pitcher enters and finishes the game without surrendering the lead in a save opportunity. ESPN's display text.
pitching_strikeoutsStringTeam pitching: Strikeouts (K). The number of times the pitcher struck out a batter. ESPN's display text.
pitching_sac_fliesStringTeam pitching: Sacrifice Flies (SF). The number of sacrifice flies surrendered. ESPN's display text.
pitching_hitsStringTeam pitching: Hits (H). The number of hits surrendered by a pitcher. ESPN's display text.
pitching_earned_runsStringTeam pitching: Earned runs (ER). The number of earned runs surrendered by a pitcher. ESPN's display text.
pitching_walksStringTeam pitching: Walks (BB). The number of times a pitcher surrenders a base on balls. ESPN's display text.
pitching_runsStringTeam pitching: Runs (R). The number of runs allowed by a pitcher. ESPN's display text.
pitching_stolen_basesStringTeam pitching: Stolen Bases (SB). The number of times a pitcher allows a baserunner to steal a base. ESPN's display text.
pitching_caught_stealingStringTeam pitching: Caught Stealing (CS). The number of times a pitcher gets out a baserunner trying to steal a base. ESPN's display text.
pitching_sac_buntsStringTeam pitching: Sacrifice Bunts (SH). The number of times a sacrifce bunt is allowed by a pitcher. ESPN's display text.
pitching_save_opportunitiesStringTeam pitching: Save Opportunities (SVOP). The number of times a pitcher enters the game with a lead of fewer than 4 runs and pitches at least one inning; enters the game with the potentional tying run on base, at bat, or on deck; or pitches three or more innings with a lead. ESPN's display text.
pitching_home_runsStringTeam pitching: Home Runs (HR). The number of times a pitcher has allowed a home run. ESPN's display text.
pitching_triplesStringTeam pitching: Triples (3B). The number of triples surrendered by the picher. ESPN's display text.
pitching_doublesStringTeam pitching: Doubles (2B). The number of doubles allowed by a pitcher. ESPN's display text.
pitching_rb_isStringTeam pitching: Runs Batted In (RBI). The number of runs scored due to the actions of the batter. ESPN's display text.
pitching_third_inningsStringTeam pitching: Third Innings Pitched (TIP). The number of third innings pitched. ESPN's display text.
pitching_pitchesStringTeam pitching: Pitches (P). The number of pitches a pitcher throws. ESPN's display text.
pitching_at_batsStringTeam pitching: At Bats (AB). The number of at bats. ESPN's display text.
pitching_full_inningsStringTeam pitching: Full Innings (FI). The number of full innings pitched by a pitcher. ESPN's display text.
pitching_part_inningsStringTeam pitching: Partial Innings (PI). The number of times a pitcher pitches a part of an inning. ESPN's display text.
pitching_eraStringTeam pitching: Earned Run Average (ERA). The average number of runs a pitcher yields per 9 innings thrown. ESPN's display text.
pitching_whipStringTeam pitching: Walks Plus Hits Per Inning Pitched (WHIP). The number representing walks plus hits divided by innings pitched. ESPN's display text.
pitching_opponent_avgStringTeam pitching: Opponent Batting Average (OBA). The opponent's batting average for a pitcher. ESPN's display text.
pitching_bipaStringTeam pitching: Balls In Play Average (BIPA). The batter's batting average when facing the pitcher without taking into account home runs or strikeouts. ESPN's display text.
pitching_total_basesStringTeam pitching: Total Bases (TB). The number of bases allowed by a pitcher. ESPN's display text.
pitching_pitch_countStringTeam pitching: Pitch Count (PC). The number of pitches thrown. ESPN's display text.
pitching_strikesStringTeam pitching: Strikes (S). The number of strikes thrown. ESPN's display text.
pitching_strike_pitch_ratioStringTeam pitching: Strike To Pitch Ratio (S/P). The ratio of strikes thrown to pitches thrown. ESPN's display text.
fielding_double_playsStringTeam fielding: Double Plays (DP). The number of double plays a fielder has been a part of as either the assister or putouter. ESPN's display text.
fielding_opportunitiesStringTeam fielding: Opportunities (OPP). The number of opportunites. ESPN's display text.
fielding_errorsStringTeam fielding: Errors (E). The number of times a fielder fails to make the play they are expected to make. ESPN's display text.
fielding_passed_ballsStringTeam fielding: Passed Balls (PB). The number of times the ball is dropped or passes by the catcher. ESPN's display text.
fielding_assistsStringTeam fielding: Assists (A). The number of times a fielder is involved in an out when the fielder is not the putouter. ESPN's display text.
fielding_outfield_assistsStringTeam fielding: Outfield Assists (OA). The number of times an outfielder fielder is involved in an out when the fielder is not the putouter. ESPN's display text.
fielding_pickoffsStringTeam fielding: Pickoffs (PO). The number of times that a pitcher or catcher throws over and picks off a baserunner. ESPN's display text.
fielding_putoutsStringTeam fielding: Putouts (PO). The number of times the fielder tags or forces the out of a baserunner. ESPN's display text.
fielding_outs_on_fieldStringTeam fielding: Outs On Field (OOF). The number of outs on field. ESPN's display text.
fielding_triple_playsStringTeam fielding: TP. The number of times that a fielder is involved in a triple play. ESPN's display text.
fielding_balls_in_zoneStringTeam fielding: Balls In Zone (BIZ). The number of balls that were batted into a fielder's zone. ESPN's display text.
fielding_outs_madeStringTeam fielding: Outs Made (OM). The number of outs made by a fielder. ESPN's display text.
fielding_hitsStringTeam fielding: Hits (H). The number of hits surrendered. ESPN's display text.
fielding_total_basesStringTeam fielding: Total Bases (TB). The number of bases allowed. ESPN's display text.
fielding_catcher_caught_stealingStringTeam fielding: Caught Stealing (CS). The number of times a catcher throws a baserunner trying to steal a base. ESPN's display text.
home_awayStringWhether the team was the home or the away side (home / away).
team_scoreInt32Runs the team scored in the game.
team_winnerBooleanTrue when the team won the game.
opponent_team_idInt64ESPN team id of the opponent.
opponent_team_locationStringOpponent city or school.
opponent_team_nameStringOpponent nickname.
opponent_team_abbreviationStringOpponent abbreviation.
opponent_team_display_nameStringFull name of the opponent, e.g. Chicago Cubs.
opponent_team_logoStringURL of the opponent's logo.
opponent_team_colorStringOpponent primary color, hex without the leading #.
opponent_team_alternate_colorStringOpponent alternate color, hex without the leading #.
opponent_team_scoreInt32Runs the opponent scored in the game.

Raises

ExceptionDescription
NoDataErrorESPN answered 404 for the game.
AssetFetchErrorThe request failed (a non-2xx answer or a connection failure after retries).

Example

from sportsdataverse.baseball.college_baseball import espn_college_baseball_team_box
team_box = espn_college_baseball_team_box(game_id=401675653)
print(team_box.shape)

# Pipeline next step (one line)

team_box.select("team_abbreviation", "batting_hits", "team_score", "team_winner")

stats.ncaa.org​

college_baseball_re24​

college_baseball_re24(seasons: 'Union[int, List[int], None]' = None, *, state: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

sportsdataverse.baseball.college_run_expectancy.college_baseball_re24 fixed to league="college_baseball".

Parameters

ParameterTypeDefaultDescription
seasonsUnion[int, List[int], None]NoneSee the core function.
stateOptional[DataFrame]NoneSee the core function.
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

see the core function's Returns table.

col_nametypedescription
base_stateString3-char base occupancy code ("_" = empty, "1"/"2"/"3" = occupied), e.g. "1_3" for runners on first and third.
outsInt64Outs at the start of the base-out state (0-2).
run_expectancyFloat64Empirical mean runs scored from this state through the end of the half-inning (RE24).
nInt64Number of plate appearances observed starting in this base-out state.

Example

from sportsdataverse.baseball.college_baseball.college_baseball_re import college_baseball_state, college_baseball_re24
state = college_baseball_state(raw)
matrix = college_baseball_re24(state=state)

college_baseball_state​

college_baseball_state(plays: 'Dict[str, Any]') -> 'pl.DataFrame'

sportsdataverse.baseball.college_run_expectancy.college_baseball_state fixed to league="college_baseball".

Parameters

ParameterTypeDefaultDescription
playsDict[str, Any]Raw payload from espn_college_baseball_game_plays(event_id, return_parsed=False).

Returns

see the core function's Returns table.

col_nametypedescription
game_idString
inningInt64
halfString
base_stateString
outsInt64
runs_beforeInt64
runs_afterInt64
batting_team_idString
play_seqInt64
score_diffInt64

Example

from sportsdataverse.baseball.college_baseball.college_baseball_re import college_baseball_state
state = college_baseball_state(raw)

college_baseball_wpa​

college_baseball_wpa(seasons: 'Union[int, List[int], None]' = None, *, state: 'Optional[pl.DataFrame]' = None, results: 'Optional[pl.DataFrame]' = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

sportsdataverse.baseball.college_run_expectancy.college_baseball_wpa fixed to league="college_baseball".

Parameters

ParameterTypeDefaultDescription
seasonsUnion[int, List[int], None]NoneSee the core function.
stateOptional[DataFrame]NoneSee the core function.
resultsOptional[DataFrame]NoneSee the core function.
return_as_pandasboolFalseReturn pandas.DataFrame instead of polars.

Returns

see the core function's Returns table.

col_nametypedescription
game_idStringESPN event id for the game (join key to the schedule).
play_seqInt64Game-global sequential plate-appearance order.
re_beforeFloat64RE24 of the base-out state before the PA.
re_afterFloat64RE24 of the base-out state after the PA.
run_valueFloat64re_after minus re_before, plus runs scored on the play.
wpaFloat64Home-perspective win-probability added.

Example

from sportsdataverse.baseball.college_baseball.college_baseball_re import college_baseball_wpa
wpa = college_baseball_wpa(state=state, results=results)

Play-by-play processing​

decompose_college_baseball_plays​

decompose_college_baseball_plays(rows: "'list[dict]'", *, return_as_pandas: 'bool' = False) -> "'Union[pl.DataFrame, pd.DataFrame]'"

Decompose pre-extracted play rows into the full PBP_SCHEMA frame.

The row-level half of parse_college_baseball_ncaa_pbp -- the play-text decomposition engine without the HTML extraction. This is the entry point for sources that already hold the base play fields, e.g. the legacy R-era baseballr-data trees (2012-2023: description/inning/ inning_top_bot/batting/fielding/score), so legacy and freshly captured games resolve into IDENTICAL pbp columns.

Parameters

ParameterTypeDefaultDescription
rowslist[dict]One dict per play. Recognized keys (all optional except description): contest_id, inning (int), inning_top_bot ("top"/"bot"), batting, fielding, play_number, score_away/score_home (ints) or a combined score string ("3-2", away-home), and description. Unrecognized keys are ignored; play_number defaults to the 1-based position in rows.
return_as_pandasboolFalseReturn a pandas.DataFrame instead of polars.

Returns

One row per input play with every text-derivable PBP_SCHEMA column populated (play_type, hit/out flags, rbi, pitch_sequence, runner movement, ...). Empty input returns a zero-row frame with the documented schema.

col_nametypedescription
contest_idString
inningInt64
inning_top_botString
battingString
fieldingString
play_numberInt64
score_awayInt64
score_homeInt64
batterStringMLBAM player id of the batter.
play_typeString
hit_trajectoryString
fielded_positionString
is_hitBoolean
is_outBoolean
strikeout_typeString
is_sacrificeBoolean
sac_typeString
is_double_playBoolean
rbiInt64
count_ballsInt64
count_strikesInt64
pitch_sequenceString
error_positionString
unearnedBoolean
runs_scoredInt64
scoring_runnersList
runners_advancedList
outs_on_playInt64
is_scoring_playBooleanFlag indicating that the play put points on the board (1 = scoring play, 0 = not).
descriptionString

Example

from sportsdataverse.baseball.college_baseball import decompose_college_baseball_plays
df = decompose_college_baseball_plays(
[{"inning": 1, "inning_top_bot": "top", "score": "0-0",
"description": "Jack Moss singled to left field (1-2 KBFX)."}]
)
print(df.select("play_type", "is_hit", "pitch_sequence").row(0))