Aan de slagGa gratis aan de slag

Run differentials with .itertuples()

The New York Yankees have made a trade with the San Francisco Giants for your analyst contract— you're a hot commodity! Your new boss has seen your work with the Giants and now wants you to do something similar with the Yankees data. He'd like you to calculate run differentials for the Yankees from the year 1962 to the year 2012 and find which season they had the best run differential.

You've remembered the function you used when working with the Giants and quickly write it down:

def calc_run_diff(runs_scored, runs_allowed):

    run_diff = runs_scored - runs_allowed

    return run_diff

Let's use .itertuples() to loop over the yankees_df DataFrame (which has been loaded into your session) and calculate run differentials.

Deze oefening maakt deel uit van de cursus

Writing Efficient Python Code

Cursus bekijken

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

run_diffs = []

# Loop over the DataFrame and calculate each row's run differential
for ____ in ____.____():
    
    runs_scored = ____
    runs_allowed = ____
Code bewerken en uitvoeren