Skip to content
Advertisement

Capture python output to variable

I’m trying to automate pybaseball from player lookup to data extraction and can’t seem to get past the first step of setting the player id as a variable.

I’m utilizing the following code to pull player id:

from pybaseball import playerid_lookup

data = playerid_lookup("kershaw", "clayton", fuzzy=True)

The output from the above lines are (exact copy/paste):

  name_last name_first  key_mlbam key_retro  key_bbref  key_fangraphs  mlb_played_first  mlb_played_last
0   kershaw    clayton     477132  kersc001  kershcl01           2036            2008.0           2022.0

Is there a method for setting the key_fangraphs number (2036) to a variable from this output?

Advertisement

Answer

As the pybaseball.playerid_lookup.playerid_lookup() method returns a pandas.DataFrame, you should be able to use the pandas.DataFrame.get() method. Something like data.get("key_fangraphs", default=-1). It would return -1 if there was no “key_fangraphs” column.

Advertisement