LoginSignup
11
8

More than 1 year has passed since last update.

もうStatcastデータには困らない!?pybaseballの紹介

Posted at

簡単に自己紹介:writing_hand:

はじめまして。とみーです。
野球×データ分析というテーマには長年興味があったので、構想はいろいろ練っていたのですが、この度記事を初めて書くことにしました。
とはいえ、初めてなので…まずは簡単に自己紹介だけ。。

  • アラサー男。一応データサイエンティストやってます:computer:
  • 野球沼の住人:baseball: (巨人ファン歴20年目。今年はプロ野球ファンクラブ完全制覇。書き出したら止まらないのでこの辺にとどめておきます)

ということで、Qiitaで野球×データ分析のテーマでいろいろ書いていけたら、と思っていますが、
今日はその第1歩として、野球に関するPythonライブラリを少し触ってみようと思います。

概要

"Baseball Libraries Python"と調べると、pybaseballpyballの2つがヒットしました。
調べる限り、2つの違いは出力結果の違いが主(※) なようなので、この記事では、より文献が多そうなpybaseballを触ってみます。

(補足) pybaseballはdataframeとして各結果を出力し、pyballはJSON形式で返すようです。詳細はこちら

前提条件

  • 端末はSurface Laptop 2
    • プロセッサ: Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz (4コア)
    • メモリ: 16GB
    • SSD: 512GB
  • 動作環境
    • ローカルのAnaconda環境 (Python3.8.8) でpip install pybaseballしました。
    • Jupyter Notebook上で"PyBaseballの使い方"の内容を実行

PyBaseballの主な機能

簡単に言えば、MLBの3大データサイトからデータを取得するライブラリです。
もう少し言うと、都度スクレイピングしなければ取れない各サイトのデータを、取得してきてくれるライブラリです。

3大データサイト (当社調べ)
  • Baseball Savant
    回転数や打球速度など、Statcastのデータを蓄積しているサイト。
    ※ StatcastについてはWikipediaでも詳細に記載されているので、そちらをご参照ください。日本でも同じもの「トラックマン」は、Statcastのデータソースの一部にあたるそうです (しらなかった:innocent::innocent:)
  • FanGraphs
    2000年代からWARなどを取りまとめているセイバーメトリクスのサイト。
  • Baseball Reference
    基礎データからWAR等のAdvanced Statsまで幅広くデータ化している大型サイト。野球以外の北米4大リーグだけでなく、サッカーまで兄弟サイトがある。

(おまけ) 余談ですが、MLBではWARはFanGraphsが算出するfWARと、Baseball Referenceが算出するbWARがあり、それぞれの値が異なることも結構興味深いポイントです。

FanGraphsとBaseball Referenceにおける2021年のWARトップ5

# fWAR (FanGraphs) bWAR (Baseball Reference)
1 大谷翔平 (8.1) 大谷翔平 (9.0)
2 Corbin Burnes (7.6) Zack Wheeler (7.6)
3 Zack Wheeler (7.4) Marcus Semien (7.3)
4 Fernando Tatis Jr. (7.3) Carlos Correa (7.2)
5 Juan Soto (7.0) Juan Soto (7.1)

順位や結果などの基礎的なチーム情報から、個人成績も、打率、防御率などの基礎情報から、WARなどセイバー指標まで、それどころか1球1球の回転数や、個々の打球の速度や角度など、日本ではなかなか公開されないレベルの情報まで、ありとあらゆる情報を取ってきてくれるライブラリです。
本記事では、PyPIで説明されている順序にのっとり、1. Statcastデータの取得、2. 個人成績の取得、3. チーム成績の取得の順で実行イメージをみていきます。

PyBaseballの使い方① Statcastデータの取得

Statcastのデータは、日付指定、または選手指定の2通りの取得方法があります。

<日付指定での取得>
任意の日付間でのすべてのStatcastデータを取得することが可能です。pybaseballのstatcastを呼び出します。ここでは、イメージとして、今年4月で日付指定をして、データ取得をしてみます。(日付指定をしない場合は、昨日のデータが取得されるようです)

<実行イメージ>

from pybaseball import statcast
data = statcast(start_dt='2022-04-01', end_dt='2022-04-30')
data.head()

<結果>

	pitch_type	game_date	release_speed	release_pos_x	release_pos_z	player_name	batter	pitcher	events	description	spin_dir	spin_rate_deprecated	break_angle_deprecated	break_length_deprecated	zone	des	game_type	stand	p_throws	home_team	away_team	type	hit_location	bb_type	balls	strikes	game_year	pfx_x	pfx_z	plate_x	plate_z	on_3b	on_2b	on_1b	outs_when_up	inning	inning_topbot	hc_x	hc_y	tfs_deprecated	tfs_zulu_deprecated	fielder_2	umpire	sv_id	vx0	vy0	vz0	ax	ay	az	sz_top	sz_bot	hit_distance_sc	launch_speed	launch_angle	effective_speed	release_spin_rate	release_extension	game_pk	pitcher.1	fielder_2.1	fielder_3	fielder_4	fielder_5	fielder_6	fielder_7	fielder_8	fielder_9	release_pos_y	estimated_ba_using_speedangle	estimated_woba_using_speedangle	woba_value	woba_denom	babip_value	iso_value	launch_speed_angle	at_bat_number	pitch_number	pitch_name	home_score	away_score	bat_score	fld_score	post_away_score	post_home_score	post_bat_score	post_fld_score	if_fielding_alignment	of_fielding_alignment	spin_axis	delta_home_win_exp	delta_run_exp
0	FF	2022-04-30	94.2	-1.62	5.94	Sawamura, Hirokazu	455139	617228	fielders_choice	hit_into_play	<NA>	<NA>	<NA>	<NA>	11	Robinson Chirinos reaches on a fielder's choic...	R	R	R	BAL	BOS	X	1	ground_ball	2	1	2022	-0.66	1.36	-0.72	3.43	<NA>	622761	663630	0	10	Bot	122.18	188.86	<NA>	<NA>	543877	<NA>	<NA>	3.822453	-137.072765	-3.849161	-9.234918	31.152066	-14.360307	3.11	1.5	31	21.6	32	94.3	2085	6.4	663364	617228	543877	666915	596115	646240	593428	657077	571771	598265	54.06	0.243	0.22	0.9	1	0	0	1	75	4	4-Seam Fastball	1	1	1	1	1	2	2	1	Strategic	Standard	210	0.195	-0.064
1	FF	2022-04-30	93.2	-1.7	6.0	Sawamura, Hirokazu	455139	617228	NaN	ball	<NA>	<NA>	<NA>	<NA>	11	Robinson Chirinos reaches on a fielder's choic...	R	R	R	BAL	BOS	B	<NA>	NaN	1	1	2022	-0.67	1.39	-0.98	4.24	<NA>	622761	663630	0	10	Bot	<NA>	<NA>	<NA>	<NA>	543877	<NA>	<NA>	3.308936	-135.653345	-1.805759	-9.001654	31.792791	-14.859073	2.64	1.25	<NA>	<NA>	<NA>	93.0	2017	6.3	663364	617228	543877	666915	596115	646240	593428	657077	571771	598265	54.19	<NA>	<NA>	<NA>	<NA>	<NA>	<NA>	<NA>	75	3	4-Seam Fastball	1	1	1	1	1	1	1	1	Strategic	Standard	212	0.0	0.148

4/30の試合が上位に来ているので、問題なく取得できていそうです (やや乱暴)。一番上が澤村投手なのはちょっと予想外すぎた

<選手指定での取得>
上記では任意の日付を指定しただけで、特に選手の指定はしませんでしたが、選手を指定することで、その選手の、指定したStatcastデータを取得することが可能です。
前提として、選手指定の際には、MLB Advanced Media IDというIDを指定する必要があり、まずはそのIDを検索する必要があります。ここでは、ブルージェイズファン歴15年なので、ブルージェイズの顔ともいえるゲレーロJr.選手を検索してみます。

<検索イメージ>

from pybaseball import playerid_lookup
### 検索時は、苗字→名前の順になるので注意
playerid_lookup('guerrero', 'vladimir')

<結果>

Gathering player lookup table. This may take a moment.
name_last	name_first	key_mlbam	key_retro	key_bbref	key_fangraphs	mlb_played_first	mlb_played_last
0	guerrero	vladimir	665489	guerv002	guerrvl02	19611	2019.0	2022.0
1	guerrero	vladimir	115223	guerv001	guerrvl01	778	1996.0	2011.0

お父様のほうも出てきましたね。ここでは、mlb_played_firstの列とmlb_played_lastの列から、最初の行がゲレーロJr.選手、2行目がお父様のゲレーロSr.さんだとわかります。
参照すべきは、key_mlbamの列で、ここから、ゲレーロJr.選手のMLB Advanced Media IDは665489であるとわかります。
ちなみに、MLBAMとはMLB Advanced Mediaの略称になります。

MLB Advanced Media IDがわかったら、そのIDを引数に、statcast_pitcherまたはstatcast_batterを呼び出します。こちらも日付指定が必要なので、ここでは、ゲレーロJr.選手の、今年4月のStatcastデータを取得をしてみます。ちなみに、こちらも同様に日付を指定しない場合は昨日のStatcastデータが返ってきます。(statcast_pitcherも同様)

<実行イメージ>

from pybaseball import statcast_batter
junior_stats = statcast_batter('2022-04-01', '2022-04-30', 665489)
junior_stats.head()

<結果>

Gathering Player Data
pitch_type	game_date	release_speed	release_pos_x	release_pos_z	player_name	batter	pitcher	events	description	...	fld_score	post_away_score	post_home_score	post_bat_score	post_fld_score	if_fielding_alignment	of_fielding_alignment	spin_axis	delta_home_win_exp	delta_run_exp
0	FF	2022-04-30	94.9	-1.77	6.42	Guerrero Jr., Vladimir	665489	677651	strikeout	called_strike	...	1	1	2	2	1	Standard	Standard	205	-0.033	-0.231
1	CH	2022-04-30	85.6	-2.07	6.21	Guerrero Jr., Vladimir	665489	677651	NaN	foul	...	1	1	2	2	1	Standard	Standard	234	0.000	0.000

Statcastのデータは、必要に応じて随時修正が入るため、過去シーズンのデータでも、後日変更になる場合があるようです。

補足として、出力結果の各カラムについて、巨人が大敗した試合中に東京ドームでまとめたものを↓に置いておきます。

(補足) Statcastの出力結果のカラム説明
  • pitch_type (球種)

    • Statcastで取得した球種のデータ
      (原文) The type of pitch derived from Statcast.
  • game_date (試合日)

    • 試合が行われた日付
      (原文) Date of the Game.
  • release_speed (初速)

    • Pitch F/X (2008〜16)、またはStatcast (2017〜) で取得した球速データ。Pitch F/Xでは、球速値は球がリリースされた瞬間の近くでの速度に補正されており、Statcastでは球がリリースされた時に球速が出るようになっている。
      (原文)Pitch velocities from 2008-16 are via Pitch F/X, and adjusted to roughly out-of-hand release point. All velocities from 2017 and beyond are Statcast, which are reported out-of-hand.
  • release_pos_x (リリース位置_x軸)

    • キャッチャー視点で見た、球の横方向のリリース位置 (単位はフィート)
      (原文) Horizontal Release Position of the ball measured in feet from the catcher's perspective.
  • release_pos_z (リリース位置_z軸)

    • キャッチャー視点で見た、球の縦方向のリリース位置 (単位はフィート)
      (原文) Vertical Release Position of the ball measured in feet from the catcher's perspective.
  • player_name (選手名)

    • 検索しているイベント (投球など) に関連した選手の名前
      (原文) Player's name tied to the event of the search.
  • batter (打者)

    • イベント発生時の打者のMLB Player ID
      (原文) MLB Player Id tied to the play event.
  • pitcher (投手)

    • イベント発生時の投手のMLB Player ID
      (原文) MLB Player Id tied to the play event.
  • events (打席結果)

    • 打席結果の内容
      (原文) Event of the resulting Plate Appearance.
  • description (結果詳細)

    • 投球の詳細 (見逃し、敬遠など)
      (原文) Description of the resulting pitch.
  • spin_dir (回転方向 (非推奨))

    • 過去に使用していたトラッキングシステムのカラム
      (原文) * Deprecated field from the old tracking system.
  • spin_rate_deprecated (回転量 (非推奨))

    • 過去に使用していたトラッキングシステムのカラム。release_spinで置き換え。
      (原文) * Deprecated field from the old tracking system. Replaced by release_spin
  • break_angle_deprecated (変化角度 (非推奨))

    • 過去に使用していたトラッキングシステムのカラム。
      (原文) * Deprecated field from the old tracking system.
  • break_length_deprecated (変化距離 (非推奨))

    • 過去に使用していたトラッキングシステムのカラム。
      (原文) * Deprecated field from the old tracking system.
  • zone (投球ゾーン)

    • キャッチャー視点で見た、投球がホームプレートを通過した時のゾーン位置
      (原文) Zone location of the ball when it crosses the plate from the catcher's perspective.
  • des (打席説明)

    • Game dayから取得した打席の説明
      (原文) Plate appearance description from game day.
  • game_type (試合種別)

    • 試合種別。E=エキシビション、S=スプリング・トレーニング、R=レギュラーシーズン、F=ワイルドカード・シリーズ、D=地区シリーズ、L=リーグ優勝決定戦、W=ワールドシリーズ
      (原文) Type of Game. E = Exhibition, S = Spring Training, R = Regular Season, F = Wild Card, D = Divisional Series, L = League Championship Series, W = World Series
  • stand (打者左右)

    • 訳称のとおり。
      (原文) Side of the plate batter is standing.
  • p_throws (投手左右)

    • 訳称のとおり。
      (原文) Hand pitcher throws with.
  • home_team (ホームチーム略称)

    • 訳称のとおり。
      (原文) Abbreviation of home team.
  • away_team (アウェイチーム略称)

    • 訳称のとおり。
      (原文) Abbreviation of away team.
  • type (結果概要)

    • 投球結果の概要。B=ボール、S=ストライク、X=インプレー
      (原文) Short hand of pitch result. B = ball, S = strike, X = in play.
  • hit_location (打球方向)

    • 最初に打球に触れた野手の守備位置
      (原文) Position of first fielder to touch the ball.
  • bb_type (打球種類)

    • 打球の種類 (ゴロ、ライナー、フライ、ポップフライ)
      (原文) Batted ball type, ground_ball, line_drive, fly_ball, popup.
  • balls (ボール)

    • 投球する直前の時点でのボールカウント
      (原文) Pre-pitch number of balls in count.
  • strikes (ストライク)

    • 投球する直前の時点でのストライクカウント
      (原文) Pre-pitch number of strikes in count.
  • game_year (試合年)

    • 試合が行われた年
      (原文) Year game took place.
  • pfx_x (横変化量)

    • キャッチャー視点で見た、横方向の変化量 (単位はフィート)
      (原文) Horizontal movement in feet from the catcher's perspective.
  • pfx_z (縦変化量)

    • キャッチャー視点で見た、縦方向の変化量 (単位はフィート)
      (原文) Vertical movement in feet from the catcher's perpsective.
  • plate_x (投球位置_横方向)

    • キャッチャー視点で見た、投球がホームプレートを通過して時点での位置
      (原文) Horizontal position of the ball when it crosses home plate from the catcher's perspective.
  • plate_z (投球位置_縦方向)

    • キャッチャー視点で見た、投球がホームプレートを通過して時点での高さ
      (原文) Vertical position of the ball when it crosses home plate from the catcher's perspective.
  • on_3b, on_2b, on_1b (1〜3塁走者ID)

    • 投球時点でそれぞれの塁にいるランナーのMLB Player ID
  • outs_when_up (アウト数)

    • 投球時点でのアウト数
      (原文) Pre-pitch number of outs.
  • inning (イニング)

    • 投球時点でのイニング
      (原文) Pre-pitch inning number.
  • inning_topbot (裏表)

    • 投球時点での回の表/裏
      (原文) Pre-pitch top or bottom of inning.
  • hc_x (打球x座標)

    • 打球のx座標
      (原文) Hit coordinate X of batted ball.
  • hc_y (打球y座標)

    • 打球のy座標
      (原文) Hit coordinate Y of batted ball.
  • tfs_deprecated (tfs (非推奨)), tfs_zulu_deprecated (tfs_zulu (非推奨))

    • 過去に使用していたトラッキングシステムのカラム
      (原文) * Deprecated field from old tracking system.
  • fielder_2 (捕手ID)

    • 投球時点での捕手のMLB Player ID
      (原文) Pre-pitch MLB Player Id of Catcher.
  • umpire (審判)

    • 過去に使用していたトラッキングシステムのカラム
      (原文) * Deprecated field from old tracking system.
  • sv_id (イベントID)

    • 試合ごとのプレイイベントのノンユニークID
      (原文) Non-unique Id of play event per game.
  • vx0 (x軸方向球速)

    • y=50フィート時点での、x軸方向の球速 (単位はフィート/秒)
      (原文) The velocity of the pitch, in feet per second, in x-dimension, determined at y=50 feet.
  • vy0 (y軸方向球速)

    • y=50フィート時点での、y軸方向の球速 (単位はフィート/秒)
      (原文) The velocity of the pitch, in feet per second, in y-dimension, determined at y=50 feet.
  • vy0 (z軸方向球速)

    • y=50フィート時点での、z軸方向の球速 (単位はフィート/秒)
      (原文) The velocity of the pitch, in feet per second, in z-dimension, determined at y=50 feet.
  • ax (x軸方向加速度)

    • y=50フィート時点での、x軸方向の球速の加速度 (単位はフィート/秒)
      (原文) The acceleration of the pitch, in feet per second per second, in x-dimension, determined at y=50 feet.
  • ay (y軸方向加速度)

    • y=50フィート時点での、y軸方向の球速の加速度 (単位はフィート/秒)
      (原文) The acceleration of the pitch, in feet per second per second, in y-dimension, determined at y=50 feet.
  • az (z軸方向加速度)

    • y=50フィート時点での、z軸方向の球速の加速度 (単位はフィート/秒)
      (原文) The acceleration of the pitch, in feet per second per second, in z-dimension, determined at y=50 feet.
  • sz_top (ストライクゾーン上辺)

    • 投球がホームプレートまで半分まで到達した時点でオペレーターが設定した、ストライクゾーンの上辺
      (原文) Top of the batter's strike zone set by the operator when the ball is halfway to the plate.
  • sz_bot (ストライクゾーン下辺)

    • 投球がホームプレートまで半分まで到達した時点でオペレーターが設定した、ストライクゾーンの下辺
      (原文) Bottom of the batter's strike zone set by the operator when the ball is halfway to the plate.
  • hit_distance (打球飛距離)

    • 打球の推測飛距離 (*CSV上はhit_distance_sc表記?)
      (原文) Projected hit distance of the batted ball.
  • launch_speed (打球速度)

    • Statcastで計測した打球の初速 (一部データは直接速度を計測できないため、予測値が含まれている。予測値の補完方法はこちら)
      (原文) Exit velocity of the batted ball as tracked by Statcast. For the limited subset of batted balls not tracked directly, estimates are included based on the process described here.
  • launch_angle (打球角度)

    • Statcastで計測した打球の角度 (一部データは直接速度を計測できないため、予測値が含まれている。予測値の補完方法はこちら)
      (原文) Launch angle of the batted ball as tracked by Statcast. For the limited subset of batted balls not tracked directly, estimates are included based on the process described here.
  • effective_speed (実質速度)

    • 投手の球持ちから推測した、打者目線での体感速度
      (原文) Derived speed based on the the extension of the pitcher's release.
  • release_spin (リリース時回転量)

    • Statcastで計測した投球の回転量 (CSV上はrelease_spin_rate表記)
      (原文) Spin rate of pitch tracked by Statcast.
  • release_extension (投手ステップ幅)

    • Statcastで計測した、投手のステップ幅 (参考)
      (原文) Release extension of pitch in feet as tracked by Statcast.
  • game_pk (ゲームID)

    • 試合ごとにユニークに割り振られるID
      (原文) Unique Id for Game.
  • pitcher (投手ID)

    • プレイイベントに紐づいた投手のMLB Player ID
      (原文) MLB Player Id tied to the play event.
  • fielder_2〜9 (捕手ID…以下略)

    • 各ポジションに対応した選手のMLB Player ID
  • release_pos_y (y軸方向リリース位置)

    • キャッチャー視点で見た、投球のリリース位置。単位はフィート。
      (原文) Release position of pitch measured in feet from the catcher's perspective.
  • estimated_ba_using_speedangle (予測打率)

    • 打球角度・打球速度から算定した予測打率
      (原文) Estimated Batting Avg based on launch angle and exit velocity.
  • estimated_woba_using_speedangle (予測wOBA)

    • 打球角度・打球速度から算定した予測wOBA
      (原文) Estimated wOBA based on launch angle and exit velocity.
  • woba_value (wOBA)

    • 打席結果に基づくwOBA値
      (原文) wOBA value based on result of play.
  • woba_denom (wOBA分母)

    • 打席結果に基づくwOBAの分母
      (原文) wOBA denominator based on result of play.
  • babip_value (BABIP)

    • 打席結果に基づくBABIP値
      (原文) BABIP value based on result of play.
  • iso_value (ISO値)

    • 打席結果に基づくISO値
      (原文) ISO value based on result of play.
  • launch_speed_angle (コンタクト結果)

    • 打球速度・打球速度に応じたコンタクトのゾーン。
      1: 弱い打球、2: 叩きつけ、3: 下を叩いた、4: ポテン、5: ソリッドコンタクト、6: バレル
      (原文) Launch speed/angle zone based on launch angle and exit velocity. 1: Weak, 2: Topped, 3: Under, 4: Flare/Burner, 5: Solid Contact, 6: Barrel
  • at_bat_number (打席数)

    • その試合における打席数
      (原文) Plate appearance number of the game.
  • pitch_number (打席内の投球数)

    • その打席における投球数
      (原文) Total pitch number of the plate appearance.
  • pitch_name (球種名)

    • Statcastデータから取得した球種名
      (原文) The name of the pitch derived from the Statcast Data.
  • home_score (投球前ホームチーム得点)

    • 投球前の時点でのホームチームの得点数
      (原文) Pre-pitch home score
  • away_score (投球前アウェイチーム得点)

    • 投球前の時点でのホームチームの得点数
      (原文) Pre-pitch away score
  • bat_score (投球前攻撃チーム得点)

    • 投球前の時点での攻撃中チームの得点数
      (原文) Pre-pitch bat team score
  • fld_score (投球前守備チーム得点)

    • 投球前の時点での守備チームの得点数
      (原文) Pre-pitch field team score
  • post_home_score (投球後ホームチーム得点)

    • 投球結果を受けたホームチームの得点数
      (原文) Post-pitch home score
  • post_away_score (投球後アウェイチーム得点)

    • 投球結果を受けたアウェイチームの得点数
      (原文) Post-pitch away score
  • post_bat_score (投球後攻撃チーム得点)

    • 投球結果を受けた攻撃中チームの得点数
      (原文) Post-pitch bat team score
  • if_fielding_alignment (内野シフト)

    • 投球時点での内野の守備シフト
      (原文) Infield fielding alignment at the time of the pitch.
  • of_fielding_alignment (外野シフト)

    • 投球時点での外野の守備シフト
      (原文) Outfield fielding alignment at the time of the pitch.
  • spin_axis (回転軸)

    • x-zの2次元平面における回転軸。0〜360の角度のスケールで、180°が純粋なバックスピンの直球、0°が純粋なトップスピン (12-6カーブと言われるもの)。
      (原文) The Spin Axis in the 2D X-Z plane in degrees from 0 to 360, such that 180 represents a pure backspin fastball and 0 degrees represents a pure topspin (12-6) curveball
  • delta_home_win_exp (Δホームチーム勝利期待値)

    • 打席前後での、ホームチームの勝利期待値の変化
      (原文) The change in Win Expectancy before the Plate Appearance and after the Plate Appearance
  • delta_run_exp (Δ得点期待値)

    • 投球前後での得点期待値の変化
      (原文) The change in Run Expectancy before the Pitch and after the Pitch

ソースはこちらなので、英語に自信のある方は、直接原文を覗いてみてください。

PyBaseballの使い方② 個人成績の取得

Statcastでだいぶ紙面を割いてしまいましたが…
FanGraphsを主なソースとして、選手の年度別成績を中心に、個人成績を取得することが可能です。

  • pitching_stats
    開始年、終了年を指定することで、その間のすべての投手成績を出力する
  • pitching_stats_range
    年度ではなく、指定した期間 (開始日~終了日) における投手成績を出力する
  • pitching_stats_bref
    pitching_statsと同様に年間成績を取得するが、ソースがFanGraphsではなくBaseball Referenceとしている。(※ ただし、ある1年の成績しか出力できないため、pitching_statsが推奨されている)

これは投手版ですが、野手版として、batting_stats, batting_stats_range, batting_stats_brefが用意されています。

簡単ですが、pitching_statsと、batting_stats_rangeだけ実行してみます。

<pitching_statsの実行イメージ>

from pybaseball import pitching_stats
pitch_data = pitching_stats(2022, 2022)
pitch_data.head()

<結果>

IDfg	Season	Name	Team	Age	W	L	WAR	ERA	G	...	LA	Barrels	Barrel%	maxEV	HardHit	HardHit%	Events	CStr%	CSW%	xERA
2	18684	2022	Sandy Alcantara	MIA	26	9	4	4.0	1.99	21	...	4.9	21	0.054	114.8	148	0.379	391	0.153	0.272	2.60
12	13743	2022	Max Fried	ATL	28	10	3	3.8	2.73	20	...	8.4	13	0.036	112.7	119	0.330	361	0.157	0.273	2.88
28	14107	2022	Kevin Gausman	TOR	31	7	8	3.8	3.30	19	...	10.4	23	0.077	116.6	116	0.391	297	0.137	0.295	3.60
22	16137	2022	Carlos Rodon	SFG	29	8	6	3.7	3.18	20	...	17.7	15	0.053	112.5	114	0.403	283	0.167	0.308	2.88
1	8700	2022	Justin Verlander	HOU	39	14	3	3.5	1.81	19	...	17.2	24	0.073	110.9	115	0.350	329	0.147	0.263	3.01
5 rows × 334 columns

いやカラム数…

<batting_stats_rangeの実行イメージ>

from pybaseball import batting_stats_range
batting_data = batting_stats_range('2022-04-01', '2022-04-30')
batting_data.head()

<結果>

Name	Age	#days	Lev	Tm	G	PA	AB	R	H	...	HBP	SH	SF	GDP	SB	CS	BA	OBP	SLG	OPS
1	C.J. Abrams	21	91	Maj-NL	San Diego	15	49	41	7	6	...	3	2	0	3	1	1	0.146	0.255	0.244	0.499
2	José Abreu	35	91	Maj-AL	Chicago	19	78	69	9	15	...	0	0	0	1	0	0	0.217	0.308	0.348	0.656

PyBaseballの使い方③ チーム成績の取得

ソースはBaseball Referenceなはずですが、チームの試合ごとの成績や、順位などの成績も取得可能です。
それぞれ、schedule_and_recordと、standingsを呼び出します。
ここでは、ブルージェイズが最後に地区優勝した2015年で検索をかけてみましょう。

<schedule_and_recordの実行イメージ>

from pybaseball import schedule_and_record
schedule_data = schedule_and_record(2015, 'TOR')
schedule_data.head()

<結果>

	Date	Tm	Home_Away	Opp	W/L	R	RA	Inn	W-L	Rank	GB	Win	Loss	Save	Time	D/N	Attendance	cLI	Streak	Orig. Scheduled
1	Monday, Apr 6	TOR	@	NYY	W	6.0	1.0	9.0	1-0	1.0	Tied	Hutchison	Tanaka	None	2:59	D	48469.0	1.07	1	None
2	Wednesday, Apr 8	TOR	@	NYY	L	3.0	4.0	9.0	1-1	2.0	0.5	Betances	Loup	Miller	2:56	N	31020.0	1.13	-1	None
3	Thursday, Apr 9	TOR	@	NYY	W	6.0	3.0	9.0	2-1	1.0	Tied	Norris	Sabathia	Castro	2:52	N	32152.0	1.03	1	None

schedule_and_recordでは、引数として、シーズンと、対象のチームの略称を渡します。略称がややこしいですが、こちらがチームと、略称の一覧になっているため、参考として使えるはず:eyes: (ちなみに過去に存在したチームもリストに記載されています)

<standingsの実行イメージ>

from pybaseball import standings
standing_data = standings(2015)[0]
standing_data

<結果>

Tm	W	L	W-L%	GB
1	Toronto Blue Jays	93	69	.574	--
2	New York Yankees	87	75	.537	6.0
3	Baltimore Orioles	81	81	.500	12.0
4	Tampa Bay Rays	80	82	.494	13.0
5	Boston Red Sox	78	84	.481	15.0

standingsでは、引数としてはシーズンを渡します。最新シーズンの場合は、最新の順位が、過去シーズンの場合は、最終順位が返されます。
また、戻り値は6つのデータフレームを格納したリストになっています。[0]がAL東地区、[1]がAL中地区、[2]がAL西地区、[3]がNL東地区、[4]がNL中地区、[5]がNL西地区となっているため、個々の地区の順位を参照するためには、[0]~[5]を指定する必要があります。

PyBaseballの使い方補足: キャッシュ

例えば、数年分のStatcastデータを取得する場合などは、どうしてもデータ取得に時間がかかってしまいます (そうは言っても、私の端末で1日1~2秒くらいで取れるので、1シーズン3分程度で取れるのですが…)。
長期データを取得する際など、回線都合でのセッション切れにより、データが消えてしまうことを防ぐために、PyBaseballではキャッシュを使用することができます。

デフォルトでは、許可なく勝手にローカルデータを使われることを嫌うユーザもいると想定し、キャッシュは無効にされていますが、2行でキャッシュが利用できるようになります。

from pybaseball import cache

cache.enable()

まとめ

と、いうことで、一球ごとのデータから、チームの年度成績まで、幅広いデータを一気に取得できるライブラリを紹介しました:triumph:
このライブラリがあれば、MLBのデータを活用した分析なんかもいろいろできそうですね…:thinking::thinking:

個人的には、こういうライブラリが日本でも出てくること、いずれは日本でもBaseball Savantのようなデータが出てきて、トラックマンのデータなどが、簡単にアクセスできるようになればいいなあ、と思ったりしています (まあ、いろいろあるんでしょうけど…)

参考リンク

GitHubリポジトリ

PyBaseballのドキュメント

PyPI上の説明

11
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8