1. Learn
  2. /
  3. Courses
  4. /
  5. Writing Efficient Python Code

Exercise

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.

Instructions 1/4

undefined XP
    1
    2
    3
    4
  • Use .itertuples() to loop over yankees_df and grab each row's runs scored and runs allowed values.