4.1. Exercises

Pivot Table Questions

Applying Pivot Table

Instructions:
Running a coding exercise for the first time could take a bit of time for everything to load. Be patient, it could take a few minutes.

When you see ____ in a coding exercise, replace it with what you assume to be the correct code. Run it and see if you obtain the desired output. Submit your code to validate if you were correct.

Make sure you remove the hash (#) symbol in the coding portions of this question. We have commented them so that the line won’t execute and you can test your code after each step.

Let’s convert the dataframe lego into wider data but this time preserve all the columns in the dataframe by using .pivot_table().

Tasks:

  • Convert the untidy data into tidy data using .pivot_table() making sure to keep all the columns.
  • Name the new dataframe tidied_lego.
  • Use .agg() to find the mean number of parts for each production year and save it in an object name year_parts_mean. (We’ve added a verb named .round() to round to the nearest whole number)
Hint 1
  • Are you using the correct arguments such as index, columns, and values?
  • Does your index contain multiple columns?
  • Are you pivoting the correct column named lego_info with values='value'?
  • Are you resetting your index again after you pivot?
  • Are you using .agg({"num_parts": "mean"})?
Fully worked solution: