Reshaping DataFrames

Learn how to reshape DataFrames to and from long format data.

Let’s now explore how we can reshape DataFrames to and from long format, and more importantly, why we would want to do so.

Melting DataFrames

One of the first things to notice is that years are spread across columns with the values corresponding to them, each in its respective cell under the respective year. The issue is that 1980 is not really a variable. A more useful way is to have a year variable, and in that column, the values vary from 1974 to 2019. Remember, the way we created the first chart in this section makes our life much easier. Let’s illustrate using a small dataset so things are clear, and then we can implement the same approach with the data DataFrame.

The Jupyter Notebook set up below shows how we can have the same data structured differently while containing the same information:

Get hands-on with 1200+ tech skills courses.