Skip to content

Instantly share code, notes, and snippets.

@Shinichi-Nakagawa
Created July 11, 2015 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shinichi-Nakagawa/76022a485a0332c2164d to your computer and use it in GitHub Desktop.
Save Shinichi-Nakagawa/76022a485a0332c2164d to your computer and use it in GitHub Desktop.
analyze_batter.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Shinichi Nakagawa'
from collections import OrderedDict
class AnalyzeBatter(object):
FIELD_POSITIONS_OF = OrderedDict([('7', 'LF'), ('8', 'CF'), ('9', 'RF')])
FIELD_POSITIONS_IF = OrderedDict([('5', '3B'), ('6', 'SS'), ('4', '2B'), ('3', '1B')])
FIELD_POSITIONS_BATTERY = OrderedDict([('2', 'C'), ('1', 'P')])
HITS_DICT = {
'HR': 'HR:Homerun',
'T': '3B:Triple',
'D': '2B:Double',
'S': '1B:Single'
}
HITS = ('HR:Homerun', '3B:Triple', '2B:Double', '1B:Single')
def __init__(self, retrosheet_util):
self._retrosheet_util = retrosheet_util
def _init_hit_charts(self, positions):
hit_chart = OrderedDict()
for pos in positions.keys():
hits = OrderedDict()
for hit in self.HITS:
hits[hit] = 0
hit_chart[positions[pos]] = hits
return hit_chart
@classmethod
def _at_bat_event(cls, at_bat_event):
if at_bat_event == 'DGR':
return 'D'
return at_bat_event
@classmethod
def _at_bat_position(cls, at_bat_position):
if len(at_bat_position) == 2:
if at_bat_position == '89':
return '9'
else:
return at_bat_position[0:1]
return at_bat_position
def hit_charts(self, df, pos_of=FIELD_POSITIONS_OF, pos_if=FIELD_POSITIONS_IF, pos_bt=FIELD_POSITIONS_BATTERY):
hit_charts = {
'of': self._init_hit_charts(pos_of),
'if': self._init_hit_charts(pos_if),
'battery': self._init_hit_charts(pos_bt)
}
for i, row in df.iterrows():
row_dict = row.to_dict()
at_bat = self._retrosheet_util.get_atbat(
row_dict['event_tx'],
row_dict['event_cd'],
row_dict['battedball_cd'],
)
at_bat_hit = AnalyzeBatter._at_bat_event(at_bat['event'])
at_bat_pos = AnalyzeBatter._at_bat_position(at_bat['position'])
if at_bat_pos in pos_of.keys():
hit_charts['of'][pos_of[at_bat_pos]][AnalyzeBatter.HITS_DICT[at_bat_hit]] += 1
continue
if at_bat_pos in pos_if.keys():
hit_charts['if'][pos_if[at_bat_pos]][AnalyzeBatter.HITS_DICT[at_bat_hit]] += 1
continue
if at_bat_pos in pos_bt.keys():
hit_charts['battery'][pos_bt[at_bat_pos]][AnalyzeBatter.HITS_DICT[at_bat_hit]] += 1
continue
return hit_charts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment