-
Notifications
You must be signed in to change notification settings - Fork 0
/
mlbstats.py
72 lines (63 loc) · 1.74 KB
/
mlbstats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import pandas as pd
import statsapi
# Common baseball stats abbreviations:
# http://m.mlb.com/glossary/standard-stats
# https://www.sportsbettingdime.com/guides/resources/baseball-stat-abbreviations/
trans = {
"gamesPlayed": "G",
"airOuts": "AO",
"runs": "R",
"doubles": "2B",
"triples": "3B",
"homeRuns": "HR",
"strikeOuts": "SO",
"baseOnBalls": "BB",
"intentionalWalks": "IBB",
"hits": "H",
"hitByPitch": "HBP",
"avg": "AVG",
"atBats": "AB",
"obp": "OBP",
"slg": "SLG",
"ops": "OPS",
"caughtStealing": "CS",
"stolenBases": "SB",
"stolenBasePercentage": "SBP",
"groundIntoDoublePlay": "GDP",
"plateAppearances": "PA",
"totalBases": "TB",
"rbi": "RBI",
"sacBunts": "SH",
"sacFlies": "SF",
"babip": "BABIP",
"groundOutsToAirouts": "GO_AO",
"atBatsPerHomeRun": "AB_HR",
"groundOuts": "GO",
"leftOnBase": "LOB",
}
def buildyears(data):
df = []
for year in data["stats"]:
d = {"season": year["season"]}
d.update(year["stats"])
df += [d]
return df
def get_player_data(name, group="hitting", lookupyear=None):
if lookupyear is not None:
players = statsapi.lookup_player(name, season=lookupyear)
else:
for year in range(2020, 1900, -1):
players = statsapi.lookup_player(name, season=year)
if len(players) > 0:
break
if len(players) > 1:
print("Results are not unique")
return None
elif len(players) == 0:
print("No results")
return None
pid = players[0]["id"]
data = statsapi.player_stat_data(pid, group, type="yearByYear")
df = pd.DataFrame(buildyears(data))
df = df.rename(columns=trans)
return df