Iam currently working to make a streamlit app for baseball sabermetrics using pybaseball. I have written a custom function to display pitching stats based upon the pitch type. Here it is :
def stats_by_pitchtypes(df):
v = df.events.fillna("None").unique()
u = ["walk","strikeout","single","double","triple","home_run","sac_fly","None"]
df1 = pd.get_dummies(df.events.fillna("None")).assign(pitch_type = df.pitch_type)
for i in u:
if i not in df1.columns:
df1[i] = 0
df1 = pd.concat([df1.groupby(["pitch_type"]).sum().assign(
PT_per = df.pitch_type.value_counts(normalize = True).round(2)*100).assign(
atbats = lambda x : x.drop(columns = "PT_per").sum(axis = 1).round(3),
Hits = lambda x : x.drop(columns = ["None","PT_per","atbats","strikeout"]).sum(axis = 1).round(3),
BA = lambda x : (x.Hits/x.atbats).round(3),
Total_bases = lambda x : (1*x.single+2*x.double+3*x.triple+4*x.home_run).round(3),
SLG = lambda x : (x.Total_bases/x.atbats).round(3),
OBP = lambda x : ((x.walk+x.Hits)/(x.walk+x.Hits+x.sac_fly)).round(4),
HR_per_AB = lambda x : (x.home_run/x.atbats).round(3),
ISO = lambda x : ((1*x.double+2*x.triple+3*x.home_run)/x.atbats).round(3),
BABIP = lambda x : ((x.Hits-x.home_run)/(x.atbats-x.strikeout-x.home_run-x.sac_fly)).round(2),
HR_per_FB = lambda x : (x.home_run/pd.get_dummies(df.bb_type,
).assign(pitch_type = df.pitch_type).groupby(
"pitch_type").sum().loc["fly_ball"])
),pd.get_dummies(df.bb_type).assign(
pitch_type = df.pitch_type
).groupby("pitch_type").sum().transform(lambda x : x/x.sum(), axis = 1).round(2)*100],axis = 1).assign(
IP = df.groupby("pitch_type")["inning"].apply(IP_cal)
).assign(Kby9 = lambda x : (x.strikeout*9)/x.IP,
WHIP = lambda x : (x.walk+x.single+x.double+x.triple+x.home_run)/x.IP)
cols = ["PT_per","BA","SLG","OBP","fly_ball","ground_ball",
"line_drive","popup","HR_per_AB","HR_per_FB","BABIP","ISO","Kby9","WHIP"]
return df1.loc[:,cols]
This is giving error when i ran the streamlit app. But when i use the app in the VS code on the same pitcher dataset.Itsnt giving a key error of flyball.
Here is the datset :
start_date = "2008-09-09"
end_date = "2021-09-09"
pitcher1 = "Jeremy Accardo"
pitcher1_df = pb.statcast_pitcher(player_id = pb.playerid_lookup(pitcher1.split(" ")[1],pitcher1.split(" ")[0])["key_mlbam"].values[0],
start_dt = start_date, end_dt = end_date).replace(pt_dict)
stats_by_pitchtypes(pitcher1_df)
Here is the error in Streamlit :
Here is the output in vs code :
can someone debug it why its giving a key error of flyball
