1. Learn
  2. /
  3. Courses
  4. /
  5. Tidy Data in Python Mini-Course

Exercise

Using Melt to Tidy Data

In df2, the years 1980, 1981, 1982, and 1983 mark the years when BMI is observed. Thus, they represent three different observations and should be seperated in three rows. A great tool to achieve this is the melt function in the pandas package. Its basic syntax is pd.melt(df, id_vars = lst), where df is the name of the dataframe we're dealing with and lst is a list of all the columns that we want to keep as columns. All the other columns will be "melted" together in different rows. To get a more concrete idea, try melt yourself to tidy the dataset df2!

Instructions

100 XP
  • Import pandas using the alias pd.
  • Melt df2! We want to maintain the Country column and melt all the rest.
  • Click "Submit" to print out the new melted DataFrame.