Skip to main content

Men's college basketball — additional Python functions — Highlights

espn_mbb_game_rosters​

espn_mbb_game_rosters(game_id: 'int', raw=False, return_as_pandas=False, **kwargs) -> 'pl.DataFrame | pd.DataFrame | dict'

espn_mbb_game_rosters() - Pull the game by id.

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from mbb_schedule().
rawboolFalseIf True, returns the Core v2 competitors payload (dict) as ESPN sent it; its roster, team and athlete $ref links are not followed.
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False, returns a polars dataframe.

Returns

Polars dataframe of game roster data with columns: 'athlete_id', 'athlete_uid', 'athlete_guid', 'athlete_type', 'first_name', 'last_name', 'full_name', 'athlete_display_name', 'short_name', 'weight', 'display_weight', 'height', 'display_height', 'age', 'date_of_birth', 'slug', 'jersey', 'linked', 'active', 'alternate_ids_sdr', 'birth_place_city', 'birth_place_state', 'birth_place_country', 'headshot_href', 'headshot_alt', 'experience_years', 'experience_display_value', 'experience_abbreviation', 'status_id', 'status_name', 'status_type', 'status_abbreviation', 'hand_type', 'hand_abbreviation', 'hand_display_value', 'draft_display_text', 'draft_round', 'draft_year', 'draft_selection', 'player_id', 'starter', 'valid', 'did_not_play', 'display_name', 'ejected', 'athlete_href', 'position_href', 'statistics_href', 'team_id', 'team_guid', 'team_uid', 'team_slug', 'team_location', 'team_name', 'team_nickname', 'team_abbreviation', 'team_display_name', 'team_short_display_name', 'team_color', 'team_alternate_color', 'is_active', 'is_all_star', 'team_alternate_ids_sdr', 'logo_href', 'logo_dark_href', 'game_id' plus the athlete's position_id, position_name, position_display_name, position_abbreviation and position_leaf. With raw=True, the competitors payload (dict).

col_nametypedescription
athlete_idInt64Unique athlete identifier (ESPN).
athlete_uidStringESPN athlete UID (universal identifier).
athlete_guidStringESPN athlete GUID.
athlete_typeStringAthlete type / class.
first_nameStringPlayer's first name.
last_nameStringPlayer's last name.
full_nameStringPlayer's full name.
athlete_display_nameStringAthlete display name (full).
short_nameStringShort display name.
weightFloat64Player weight in pounds.
display_weightStringPlayer weight in display format (e.g. '180 lbs').
heightFloat64Player height (string e.g. '6-2' or inches).
display_heightStringPlayer height in display format (e.g. '6-2').
ageInt64Player age (in years).
date_of_birthStringDate of birth (YYYY-MM-DD).
slugStringURL-safe identifier.
jerseyStringJersey number worn by the player.
linkedBooleanTRUE if the record is linked to a related entity.
activeBooleanTRUE if the row represents an active record (player / team / season).
alternate_ids_sdrString
birth_place_cityStringBirth place city.
birth_place_stateStringBirth place state.
birth_place_countryStringBirth place country.
birth_country_alternate_idInt64Alternate identifier for the player's birth country as provided by ESPN.
birth_country_abbreviationString
headshot_hrefStringHeadshot image URL.
headshot_altStringAlternative-text label for the headshot.
flag_hrefStringURL to the player's country flag image as supplied by ESPN.
flag_altStringAlt-text string for the player's country flag image, typically the country name.
flag_relStringRelationship descriptor for the country flag link, indicating the link type (e.g., 'country-flag').
experience_yearsInt64Experience years.
experience_display_valueStringExperience display value.
experience_abbreviationStringExperience abbreviation.
status_idInt64Status identifier.
status_nameStringStatus label.
status_typeStringStatus type.
status_abbreviationStringStatus abbreviation.
position_idInt64ESPN's numeric identifier of the athlete's listed position (the Core v2 position resource id).
position_nameStringName of the athlete's listed position from ESPN's position resource, e.g. Guard or Forward.
position_display_nameStringDisplay form of the athlete's listed position as ESPN renders it; usually equal to position_name.
position_abbreviationStringShort code of the athlete's listed position (e.g. G, F, RW, OL), from ESPN's position resource.
position_leafBooleanWhether the position is a leaf of ESPN's position tree; False marks a grouping, not a specific role.
hand_typeStringHand type.
hand_abbreviationStringHand abbreviation.
hand_display_valueStringHand display value.
starterBooleanTRUE if the player was in the starting lineup; FALSE otherwise.
jersey_rightStringRight-justified or secondary jersey number display string for the player.
validBooleanValid.
did_not_playBooleanTRUE if the player did not appear in the game.
display_nameStringDisplay name.
ejectedBooleanTRUE if the player was ejected from the game.
athlete_hrefStringESPN API URL pointing to the full athlete resource for this player.
position_hrefStringESPN API URL pointing to the full position resource for this player's role.
statistics_hrefStringESPN API URL pointing to the player's statistics resource for this game.
team_idInt64Unique team identifier.
orderInt64Display order within the result set.
home_awayStringGame venue label ('home' or 'away').
winnerBooleanWinner.
team_guidStringESPN team GUID.
team_uidStringESPN universal team identifier (UID format 's:40~l:...~t:...').
team_slugStringURL-safe team identifier (e.g. 'lasvegas-aces' / 'aces').
team_locationStringTeam city or location string.
team_nameStringFull team display name (e.g. 'Las Vegas Aces').
team_nicknameStringTeam nickname.
team_abbreviationStringShort team abbreviation (e.g. 'LAS').
team_display_nameStringFull team display name.
team_short_display_nameStringShort team display name (e.g. 'Aces').
team_colorStringTeam primary color (hex without leading '#').
team_alternate_colorStringTeam alternate color (hex without leading '#').
is_activeBooleanIs active.
is_all_starBooleanIs all star.
team_alternate_ids_sdrStringAlternate team identifier from ESPN's SDR (Sports Data Repository) system.
logo_hrefStringTeam or league logo URL.
logo_dark_hrefStringLogo URL for dark backgrounds.
game_idInt64Unique game identifier.

Raises

ExceptionDescription
NoDataErrorESPN has no competitors, roster or athlete resource for the game (404), or every rostered athlete's $ref answered 404. A single 404 athlete is left out with a UserWarning and the rest of the roster is returned.
AssetFetchErrorA fetch failed (403, 429, 5xx, a dropped connection); never treated as a missing athlete.

Example

from sportsdataverse.mbb import espn_mbb_game_rosters
roster = espn_mbb_game_rosters(game_id=401638637)
print(roster.shape)

# Identify starters

import polars as pl
starters = roster.filter(pl.col("starter") == True).select(
["full_name", "jersey", "team_display_name"]
)

# Pandas round-trip

roster_pd = espn_mbb_game_rosters(game_id=401638637, return_as_pandas=True)
roster_pd.head()

espn_mbb_pbp​

espn_mbb_pbp(game_id: 'int', raw: 'bool' = False, return_parsed: 'bool' = True, return_as_pandas: 'bool' = False, **kwargs)

espn_mbb_pbp() - Pull one game's play-by-play from ESPN's mens-college-basketball/summary endpoint.

By default the plays come back as the frame the espn_mens_college_basketball_pbp release publishes (what ~sportsdataverse.mbb.load_mbb_pbp reads): snake_case columns, Int32 team / athlete / game ids, the Int64 play id, game_date / game_date_time, the hoopR shot coordinates, athlete_name_{1,2,3}, and home_score / away_score rebuilt from the scoring plays when that reproduces the final (score_source says which). The release's season-level pregame_home_prob / home_win_prob are not added.

Parameters

ParameterTypeDefaultDescription
game_idintUnique game_id, can be obtained from mbb_schedule().
rawboolFalseIf True, returns the raw json from the API endpoint (wins over return_parsed).
return_parsedboolTrueIf True (default), returns the release play-by-play frame. If False, returns the game dictionary (the shape before 0.2.0, which helper_mbb_play_by_play / helper_mbb_team_box / helper_mbb_player_box and game_page_frames read).
return_as_pandasboolFalseIf True, returns the frame as pandas instead of polars. Ignored with raw=True or return_parsed=False, which return a dict.

Returns

One row per play, columns (in order) and dtypes as the release (load_mbb_pbp) for that season; a pandas frame with return_as_pandas=True. Zero rows, with the release's columns, when ESPN has no play-by-play for the game (playByPlaySource == "none") or 10 or fewer plays (hoopR returns NULL). A game with no betting line has null spread, home-favorite and home-team-spread values on every play and the spread-available flag False (hoopR's NA), never a default line. With return_parsed=False, a dictionary of game data with keys: "gameId", "plays", "winprobability", "boxscore", "header", "format", "broadcasts", "videos", "playByPlaySource", "standings", "article", "leaders", "timeouts", "pickcenter", "againstTheSpread", "odds", "predictor", "espnWP", "gameInfo", "teamInfo", "season".

Example

from sportsdataverse.mbb import espn_mbb_pbp
plays = espn_mbb_pbp(game_id=401638645)
print(plays.shape)

# Filter shooting plays for a basic shot chart

import polars as pl
shots = plays.filter(pl.col("shooting_play") == True)
shots.select(
[
"period_number",
"clock_display_value",
"team_id",
"coordinate_x",
"coordinate_y",
"score_value",
"text",
]
).head()

# As pandas

plays_pd = espn_mbb_pbp(game_id=401638645, return_as_pandas=True)
plays_pd[plays_pd["shooting_play"] == True].head()

# The game dictionary (box score, header, pickcenter, ...)

game = espn_mbb_pbp(game_id=401638645, return_parsed=False)
print(game["gameId"], len(game["plays"]))

# Raw payload (skip the cleaning pipeline) for debugging

raw = espn_mbb_pbp(game_id=401638645, raw=True)
sorted(raw.keys())

espn_mbb_player_stats​

espn_mbb_player_stats(athlete_id: 'int', season: 'int', *, season_type: 'str' = 'regular', total: 'bool' = False, raw: 'bool' = False, return_as_pandas: 'bool' = False, **kwargs: 'Any') -> 'pl.DataFrame | pd.DataFrame | dict[str, Any]'

Pull a men's-college-basketball athlete's ESPN season stat line.

See sportsdataverse.wbb.espn_wbb_player_stats for full documentation of the wide return shape, the {category}_{stat} stat columns, the athlete / team metadata blocks, and the season_type / total parameters. For the richer web-v3 payload use sportsdataverse.mbb.espn_mbb_player_stats_v3.

Parameters

ParameterTypeDefaultDescription
athlete_idintESPN men's-college-basketball athlete identifier.
seasonintSeason year, used in the core-v2 path.
season_typestr'regular'"regular" (type 2) or "postseason" (type 3).
totalboolFalseForward-compat totals passthrough.
rawboolFalseIf True, returns the raw core-v2 statistics JSON dict.
return_as_pandasboolFalseIf True, returns a pandas DataFrame; else polars.

Returns

A single-row wide DataFrame (polars by default). When raw=True returns the raw statistics JSON dict.

col_nametypedescription
seasonInt64Season year.
season_typeStringSeason type (1=pre-season, 2=regular season, 3=postseason, 4=off-season for ESPN; or string label for WNBA Stats).
totalBooleanTotal.
athlete_idInt64Unique athlete identifier (ESPN).
athlete_uidStringESPN athlete UID (universal identifier).
athlete_guidStringESPN athlete GUID.
athlete_typeStringAthlete type / class.
first_nameStringPlayer's first name.
last_nameStringPlayer's last name.
full_nameStringPlayer's full name.
display_nameStringDisplay name.
short_nameStringShort display name.
weightFloat64Player weight in pounds.
display_weightStringPlayer weight in display format (e.g. '180 lbs').
heightFloat64Player height (string e.g. '6-2' or inches).
display_heightStringPlayer height in display format (e.g. '6-2').
ageStringPlayer age (in years).
date_of_birthStringDate of birth (YYYY-MM-DD).
jerseyStringJersey number worn by the player.
slugStringURL-safe identifier.
activeBooleanTRUE if the row represents an active record (player / team / season).
position_idInt64Unique position identifier.
position_nameStringListed roster position ('Guard', 'Forward', 'Center').
position_display_nameStringPosition display name.
position_abbreviationStringPosition abbreviation ('G' / 'F' / 'C').
college_nameStringCollege / pre-draft team.
status_idInt64Status identifier.
status_nameStringStatus label.
defensive_blocksFloat64Short for blocked shot, number of times when a defensive player legally deflects a field goal attempt from an offensive player.
defensive_defensive_reboundsFloat64The number of times when the defense obtains the possession of the ball after a missed shot by the offense.
defensive_stealsFloat64The number of times a defensive player forced a turnover by intercepting or deflecting a pass or a dribble of an offensive player.
defensive_turnover_pointsFloat64The amount of points resulting from the possession following a turnover.
defensive_avg_defensive_reboundsFloat64The average defensive rebounds per game.
defensive_avg_blocksFloat64The average blocks per game.
defensive_avg_stealsFloat64The average steals per game.
general_disqualificationsFloat64The number of times a player reached the foul limit.
general_flagrant_foulsFloat64The number of fouls that the officials thought were unnecessary or excessive.
general_foulsFloat64The number of times a player had illegal contact with the opponent.
general_perFloat64A numerical value for each of a player's accomplishments per-minute and is pace-adjusted for the team they play on. The league average in PER to 15.00 every season.
general_ejectionsFloat64The number of times a player or coach is removed from the game as a result of a serious offense.
general_technical_foulsFloat64The number of times an player or coach was called for a technical foul (unsportsmanlike conduct or violations).
general_reboundsFloat64The total number of rebounds (offensive and defensive).
general_minutesFloat64The total number of minutes played.
general_avg_minutesFloat64The average number of minutes per game.
general_fantasy_ratingFloat64The Fantasy Rating of a player.
general_plus_minusFloat64A player's estimated on-court impact on team performance measured in point differential per 100 possessions.
general_avg_reboundsFloat64The average rebounds per game.
general_avg_foulsFloat64The average fouls committed per game.
general_avg_flagrant_foulsFloat64The average number of flagrant fouls per game.
general_avg_technical_foulsFloat64The average number of technical fouls per game.
general_avg_ejectionsFloat64The average ejections per game.
general_avg_disqualificationsFloat64The average number of disqualifications per game.
general_assist_turnover_ratioFloat64The average number of assists a player or team records per turnover.
general_steal_foul_ratioFloat64The average number of steals a player or team records per foul committed.
general_block_foul_ratioFloat64The average number of blocks a player or record per foul committed.
general_avg_team_reboundsFloat64The average number of rebounds for a team per game.
general_total_reboundsFloat64The total number of rebounds for a team or player.
general_total_technical_foulsFloat64The total number of technical fouls for a team or player.
general_steal_turnover_ratioFloat64The number of steals per turnover.
general_games_playedFloat64Games Played.
general_games_startedFloat64The number of games started by an athlete.
general_double_doubleFloat64The number of times double digit values were accumulated in 2 of the following categories: points, rebounds, assists, steals, and blocked shots.
general_triple_doubleFloat64The number of times double digit values were accumulated in 3 of the following categories: points, rebounds, assists, steals, and blocked shots.
offensive_assistsFloat64The number of times a player who passes the ball to a teammate in a way that leads to a score by field goal, meaning that he or she was "assisting" in the basket. There is some judgment involved in deciding whether a passer should be credited with an assist.
offensive_field_goalsFloat64Field Goal makes and attempts.
offensive_field_goals_attemptedFloat64The number of times a 2pt field goal was attempted.
offensive_field_goals_madeFloat64The number of times a 2pt field goal was made.
offensive_field_goal_pctFloat64The ratio of field goals made to field goals attempted: FGM / FGA.
offensive_free_throwsFloat64Free Throw makes and attempts.
offensive_free_throw_pctFloat64The ratio of free throws made to free throws attempted: FTM / FTA.
offensive_free_throws_attemptedFloat64The number of times a free throw was attempted.
offensive_free_throws_madeFloat64The number of times a free throw was made.
offensive_offensive_reboundsFloat64The number of times when the offense obtains the possession of the ball after a missed shot.
offensive_pointsFloat64The number of points scored.
offensive_turnoversFloat64The number of times a player loses possession to the other team.
offensive_three_point_field_goals_attemptedFloat64The number of times a 3pt field goal was attempted.
offensive_three_point_field_goals_madeFloat64The number of times a 3pt field goal was made.
offensive_total_turnoversFloat64The number of turnovers plus team turnovers for the team.
offensive_points_in_paintFloat64The amount of points scored in the area known as "the Paint"(the rectangle between the foul line and the baseline).
offensive_second_chance_pointsFloat64Total points scored by the player on second-chance opportunities following an offensive rebound.
offensive_fast_break_pointsFloat64The number of points scored on fast breaks.
offensive_avg_field_goals_madeFloat64The average field goals made per game.
offensive_avg_field_goals_attemptedFloat64The average field goals attempted per game.
offensive_avg_three_point_field_goals_madeFloat64The average three point field goals made per game.
offensive_avg_three_point_field_goals_attemptedFloat64The average three point field goals attempted per game.
offensive_avg_free_throws_madeFloat64The average free throw shots made per game.
offensive_avg_free_throws_attemptedFloat64The average free throw shots attempted per game.
offensive_avg_pointsFloat64The average number of points scored per game.
offensive_avg_offensive_reboundsFloat64The average offensive rebounds per game.
offensive_avg_assistsFloat64The average assists per game.
offensive_avg_turnoversFloat64The average turnovers committed per game.
offensive_offensive_rebound_pctFloat64The percentage of the number of times they obtain the possession of the ball after a missed shot.
offensive_estimated_possessionsFloat64An estimation of the number of possessions for a team or player.
offensive_avg_estimated_possessionsFloat64The average number of estimated possessions per game for a team or player.
offensive_points_per_estimated_possessionsFloat64The number of points per estimated possession for a team or player.
offensive_avg_team_turnoversFloat64The average number of turnovers for a team per game.
offensive_avg_total_turnoversFloat64The average number of total turnovers for a team per game.
offensive_three_point_field_goal_pctFloat64The ratio of 3pt field goals made to 3pt field goals attempted: 3PM / 3PA.
offensive_two_point_field_goals_madeFloat64The number of 2-point field goals made for a team or player.
offensive_two_point_field_goals_attemptedFloat64The number of 2-point field goals attempted for a team or player.
offensive_avg_two_point_field_goals_madeFloat64The number of 2-point field goals made per game for a team or player.
offensive_avg_two_point_field_goals_attemptedFloat64The number of 2-point field goals attempted per game for a team or player.
offensive_two_point_field_goal_pctFloat64The percentage of 2-points fields goals made by a team or player.
offensive_shooting_efficiencyFloat64The efficiency with which a team or player shoots the basketball.
offensive_scoring_efficiencyFloat64The efficiency with which a team or player scores the basketball.
team_idInt64Unique team identifier.
team_uidStringESPN universal team identifier (UID format 's:40~l:...~t:...').
team_guidStringESPN team GUID.
team_slugStringURL-safe team identifier (e.g. 'lasvegas-aces' / 'aces').
team_locationStringTeam city or location string.
team_nameStringFull team display name (e.g. 'Las Vegas Aces').
team_abbreviationStringShort team abbreviation (e.g. 'LAS').
team_display_nameStringFull team display name.
team_short_display_nameStringShort team display name (e.g. 'Aces').
team_colorStringTeam primary color (hex without leading '#').
team_alternate_colorStringTeam alternate color (hex without leading '#').
team_is_activeBooleanTRUE if the team is currently active.
team_logo_hrefString

Raises

ExceptionDescription
ValueErrorseason_type is not "regular"/"postseason".
sportsdataverse.errors.NoDataErrorESPN returned 404.
sportsdataverse.errors.AssetFetchErrorThe statistics, athlete or team fetch failed (403, 429, 5xx, a dead connection); only a 404 on the athlete or team node leaves those columns null.

Example

from sportsdataverse.mbb import espn_mbb_player_stats
df = espn_mbb_player_stats(athlete_id=4395624, season=2023)
df.select(["full_name", "team_display_name", "offensive_points"])

espn_mbb_schedule​

espn_mbb_schedule(dates=None, groups=50, season_type=None, limit=500, return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_mbb_schedule - look up the men's college basketball scheduler for a given season

Parameters

ParameterTypeDefaultDescription
datesintNoneA date (YYYYMMDD) or a season (YYYY, 2002 or later). A season reads that season's game days from ESPN's scoreboard calendar and requests each day in turn (one calendar request plus ~150 day requests), keeping the games ESPN files under the season, sorted by date. A day that fails raises AssetFetchError.
groupsint50Used to define different divisions. 50 is Division I, 51 is Division II/Division III.
season_typeintNone2 for regular season, 3 for post-season, 4 for off-season.
limitint500number of records to return, default: 500. A season pull sends it per day, capped at 1000 (ESPN answers 25 events above that), and raises AssetFetchError for a day that fills it.
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False, returns a polars dataframe.

Returns

Polars dataframe containing schedule dates for the requested season. A day or season with no games returns a zero-row frame carrying the documented columns.

col_nametypedescription
idInt64Id.
uidStringESPN UID string.
dateStringDate in YYYY-MM-DD format.
attendanceInt64Reported attendance.
time_validBooleanTime valid.
neutral_siteBooleanNeutral site.
conference_competitionBooleanConference competition.
play_by_play_availableBoolean
recentBooleanRecent.
tournament_idInt64ESPN tournament identifier.
start_dateStringStart date (YYYY-MM-DD).
broadcastStringBroadcast information string.
highlightsString
notes_typeStringNotes type.
notes_headlineStringNotes headline.
broadcast_marketStringBroadcast market label (e.g. 'national', 'home').
broadcast_nameStringBroadcast name.
type_idInt64Type identifier (numeric).
type_abbreviationStringType abbreviation.
venue_idInt64Unique venue identifier.
venue_full_nameStringVenue full name.
venue_address_cityStringVenue address city.
venue_address_stateStringVenue address state / region.
venue_indoorBooleanTRUE if the venue is indoors.
status_clockFloat64Status clock.
status_display_clockStringStatus display clock.
status_periodInt64Status period.
status_type_idInt64Unique identifier for status type.
status_type_nameStringStatus type name.
status_type_stateStringStatus type state.
status_type_completedBooleanStatus type completed.
status_type_descriptionStringStatus type description.
status_type_detailStringStatus type detail.
status_type_short_detailStringStatus type short detail.
format_regulation_periodsInt64Format regulation periods.
home_idInt64Unique identifier for home.
home_uidStringHome team's uid.
home_locationStringHome team's location.
home_nameStringHome name.
home_abbreviationStringHome team's abbreviation.
home_display_nameStringHome display name.
home_short_display_nameStringHome short display name.
home_colorStringColor code (hex) for home.
home_alternate_colorStringColor code (hex) for home alternate.
home_is_activeBooleanHome team's is active.
home_venue_idInt64Unique identifier for home venue.
home_logoStringHome team logo URL.
home_conference_idInt64Unique identifier for home conference.
home_scoreStringHome team score at the time of the play.
home_winnerBooleanHome team's winner.
home_current_rankInt64Current national poll ranking of the home team at the time of the game, or null if unranked.
home_linescoresListPeriod-by-period scoring breakdown for the home team, serialized as a packed integer sequence.
home_recordsStringWin-loss record string(s) for the home team across applicable record categories (e.g., overall, conference).
away_idInt64Unique identifier for away.
away_uidStringAway team's uid.
away_locationStringAway team's location.
away_nameStringAway name.
away_abbreviationStringAway team's abbreviation.
away_display_nameStringAway display name.
away_short_display_nameStringAway short display name.
away_colorStringColor code (hex) for away.
away_alternate_colorStringColor code (hex) for away alternate.
away_is_activeBooleanAway team's is active.
away_venue_idInt64Unique identifier for away venue.
away_logoStringAway team logo URL.
away_conference_idInt64Unique identifier for away conference.
away_scoreStringAway team score at the time of the play.
away_winnerBooleanAway team's winner.
away_current_rankInt64Current national poll ranking of the away team at the time of the game, or null if unranked.
away_linescoresListPeriod-by-period scoring breakdown for the away team, serialized as a packed integer sequence.
away_recordsStringWin-loss record string(s) for the away team across applicable record categories (e.g., overall, conference).
game_idInt64Unique game identifier.
seasonInt64Season year.
season_typeInt64Season type (1=pre-season, 2=regular season, 3=postseason, 4=off-season for ESPN; or string label for WNBA Stats).
home_logo_darkString
away_logo_darkString

Example

from sportsdataverse.mbb import espn_mbb_schedule
day = espn_mbb_schedule(dates=20240408)
print(day.shape)

# Season-level pull (2024 season)

season = espn_mbb_schedule(dates=2024)
print(season.shape)

# Filter to a specific team (Duke ``team_id=150``)

import polars as pl
duke = season.filter(
(pl.col("home_id") == 150) | (pl.col("away_id") == 150)
)

# Pandas round-trip

season_pd = espn_mbb_schedule(dates=2024, return_as_pandas=True)
season_pd.head()

espn_mbb_teams​

espn_mbb_teams(groups=None, return_as_pandas=False, **kwargs) -> 'pl.DataFrame'

espn_mbb_teams - look up the men's college basketball teams

Parameters

ParameterTypeDefaultDescription
groupsintNoneUsed to define different divisions. 50 is Division I, 51 is Division II/Division III.
return_as_pandasboolFalseIf True, returns a pandas dataframe. If False, returns a polars dataframe.

Returns

Polars dataframe of the men's college basketball teams, one row per team, with the columns in the returns table. A payload without teams returns a zero-row frame with those columns. The result is not cached: every call fetches (through the package's opt-in TTL response cache, sportsdataverse.cache, when it is on).

col_nametypedescription
team_abbreviationStringShort team abbreviation (e.g. 'LAS').
team_alternate_colorStringTeam alternate color (hex without leading '#').
team_colorStringTeam primary color (hex without leading '#').
team_display_nameStringFull team display name.
team_idInt64Unique team identifier.
team_is_activeBooleanTRUE if the team is currently active.
team_is_all_starBooleanTRUE if the row represents an All-Star team.
team_locationStringTeam city or location string.
team_logosInt64
team_nameStringFull team display name (e.g. 'Las Vegas Aces').
team_nicknameStringTeam nickname.
team_short_display_nameStringShort team display name (e.g. 'Aces').
team_slugStringURL-safe team identifier (e.g. 'lasvegas-aces' / 'aces').
team_uidStringESPN universal team identifier (UID format 's:40~l:...~t:...').

Raises

ExceptionDescription
NoDataErrorESPN answered 404 for the teams resource.
AssetFetchErrorThe fetch failed (403, 429, 5xx, a dropped connection); never returned as an empty frame.

Example

from sportsdataverse.mbb import espn_mbb_teams
teams = espn_mbb_teams()
print(teams.shape)
print(teams.columns[:8])

# Walk every team-id (handy for batched scrapes)

team_ids = teams["team_id"].to_list()
print(len(team_ids), "D1 teams")

# Pandas round-trip + Division II/III

d2_d3 = espn_mbb_teams(groups=51, return_as_pandas=True)
d2_d3.head()

most_recent_mbb_season​

most_recent_mbb_season()

Return the most recent men's college basketball season year.

The men's college basketball season spans early November through early April; for any month October-December the "current season" is the following calendar year (e.g. October 2025 returns 2026).

Returns

The most recent / current season year.

Example

from sportsdataverse.mbb import most_recent_mbb_season, espn_mbb_schedule
season = most_recent_mbb_season()
sched = espn_mbb_schedule(dates=season)

ncaa_mbb_play_by_play​

ncaa_mbb_play_by_play(game_ids: "'Sequence[object]'", *, fetcher: 'Optional[_SupportsFetchGamePbp]' = None, return_as_pandas: 'bool' = False, errors: "Literal['raise', 'skip']" = 'raise') -> "'Union[pl.DataFrame, Any]'"

Scrape many MBB games' play-by-play (bigballR get_play_by_play).

Ports bigballR/R/all_functions.R:1857-1897: drops missing ids, shares one fetcher session across games, retries each empty/failed game once (except a page the format guard rejected: its layout cannot change on a re-fetch), row-binds the survivors, and logs the removed ids.

Parameters

ParameterTypeDefaultDescription
game_idsSequence[object]NCAA contest ids; None/NaN entries and non-integral floats (6470186.5) are dropped, an integral float (6470186.0) is read as "6470186".
fetcherOptional[_SupportsFetchGamePbp]NoneOptional injected fetcher exposing fetch_game_pbp. Defaults to one shared NcaaFetcher.with_browser() context.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.
errorsLiteral['raise', 'skip']'raise'"raise" (default): a failed fetch (a ban, an exhausted proxy pool, an uncleared challenge) raises AssetFetchError. "skip": it is dropped like a missing game, and the frame gains a scrape_status column -- "ok" on every play row, plus one row per dropped game (game_id and why: fetch_failed: ..., no_data: ..., request_error: ..., parse_failed: ..., unsupported_layout: <format> for a page in a layout the parser does not read, or empty).

Returns

Row-bound play-by-play for every game that scraped successfully (zero-row contract frame when none did). A missing game or a page the parser cannot read is dropped and logged (bigballR parity).

col_nametypedescription
game_idStringUnique game identifier.
game_dateStringGame date (YYYY-MM-DD).
homeStringHome.
awayStringAway record.
periodInt64Period of the game (1-4 quarters; 5+ for OT).
clockStringGame clock value.
game_timeStringGame start time.
game_secondsInt64
home_scoreInt64Home team score at the time of the play.
away_scoreInt64Away team score at the time of the play.
event_teamString
event_descriptionString
player_1String
player_2String
event_typeStringEvent / play type code (V2 PBP).
event_resultString
shot_valueInt64Point value of the shot (2 or 3).
event_lengthInt64
poss_numInt64
poss_teamString
poss_lengthInt64
is_transitionBoolean
home_1String
home_2String
home_3String
home_4String
home_5String
away_1String
away_2String
away_3String
away_4String
away_5String
statusStringStatus label.
is_garbage_timeBoolean
sub_deviateInt64

Raises

ExceptionDescription
AssetFetchErrorA fetch failed and errors="raise".
ValueErrorerrors is not "raise" or "skip".

Example

from sportsdataverse.mbb.mbb_ncaa_game_pbp import ncaa_mbb_play_by_play
df = ncaa_mbb_play_by_play(["6470186", "6479639"])
print(df.shape)

# Pipeline next step (one line)

df.group_by("game_id").len()

ncaa_mbb_team_roster​

ncaa_mbb_team_roster(team_id: 'Optional[int]' = None, *, team: 'Optional[str]' = None, season: 'Optional[str]' = None, fetcher: "Optional['NcaaFetcher']" = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Scrape a men's team roster from stats.ncaa.org.

Port of bigballR get_team_roster. The player column is the normalized FIRST.LAST key that byte-matches the play-by-play name normalization, so roster<->pbp joins line up.

Parameters

ParameterTypeDefaultDescription
team_idOptional[int]Nonestats.ncaa.org team id (changes every season).
teamOptional[str]NoneSchool name, e.g. "Illinois".
seasonOptional[str]NoneSeason string, e.g. "2025-26"; required with team.
fetcherOptional['NcaaFetcher']NoneInjectable ~sportsdataverse.mbb.mbb_ncaa_fetch. NcaaFetcher; defaults to a fresh browser-transport fetcher.
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per player -- see parse_ncaa_bb_team_roster for the column contract.

col_nametypedescription
gpStringGames played.
gsStringGames started.
jerseyStringJersey number worn by the player.
nameStringDisplay name.
classStringCollege class / draft eligibility note.
positionStringListed roster position (G, F, C, etc.).
heightStringPlayer height (string e.g. '6-2' or inches).
hometownStringPlayer hometown.
high_schoolString
playerStringPlayer name.
clean_nameString
ht_inchesInt64
player_idStringUnique player identifier.

Raises

ExceptionDescription
ValueErrorNeither team_id nor a resolvable team/season pair was given.

Example

from sportsdataverse.mbb import ncaa_mbb_team_roster
df = ncaa_mbb_team_roster(team="Illinois", season="2025-26")
print(df.select("jersey", "player", "ht_inches").head())

ncaa_mbb_team_schedule​

ncaa_mbb_team_schedule(team_id: 'Optional[int]' = None, *, team: 'Optional[str]' = None, season: 'Optional[str]' = None, fetcher: "Optional['NcaaFetcher']" = None, return_as_pandas: 'bool' = False) -> "Union[pl.DataFrame, 'pd.DataFrame']"

Scrape a men's team's season schedule from stats.ncaa.org.

Port of bigballR get_team_schedule. Give either the season-specific team_id or a team + season pair (resolved through the bundled men's crosswalk).

Parameters

ParameterTypeDefaultDescription
team_idOptional[int]Nonestats.ncaa.org team id (changes every season) -- the number in the team page URL.
teamOptional[str]NoneSchool name, e.g. "Illinois" (not the mascot form).
seasonOptional[str]NoneSeason string, e.g. "2025-26"; required with team.
fetcherOptional['NcaaFetcher']NoneInjectable ~sportsdataverse.mbb.mbb_ncaa_fetch. NcaaFetcher; defaults to a fresh browser-transport fetcher (stats.ncaa.org blocks plain HTTP clients).
return_as_pandasboolFalseReturn a pandas DataFrame instead of polars.

Returns

One row per scheduled game -- see parse_ncaa_bb_team_schedule for the column contract.

col_nametypedescription
game_dateStringGame date (YYYY-MM-DD).
homeStringHome.
home_scoreInt64Home team score at the time of the play.
awayStringAway record.
away_scoreInt64Away team score at the time of the play.
box_idString
game_idStringUnique game identifier.
is_neutralBoolean
detailStringDetail.
attendanceInt64Reported attendance.

Raises

ExceptionDescription
ValueErrorNeither team_id nor a resolvable team/season pair was given.

Example

import polars as pl
from sportsdataverse.mbb import ncaa_mbb_team_schedule
df = ncaa_mbb_team_schedule(team="Illinois", season="2025-26")
print(df.shape)

# Pipeline next step (one line)

df.filter(pl.col("is_neutral") == True).head()