Using unstack and pivot to reshape data from long to wide format
Sometimes, we actually have to move data from a tidy to an untidy structure. This is often because we need to prepare the data for analysis with software packages that do not handle relational data well, or because we are submitting data to some external authority that has requested it in an untidy format. unstack
and pivot
can be helpful when we need to reshape data from long to wide format. unstack
does the opposite of what we did with stack
, and pivot
does the opposite of melt
.
Getting ready
We continue to work with the NLS data on weeks worked and college enrollment in this recipe.
How to do it…
We use unstack
and pivot
to return the melted NLS DataFrame to its original state:
- Import
pandas
and load the stacked and melted NLS data:import pandas as pd nls97 = pd.read_csv("data/nls97g.csv", low_memory=False) nls97.set_index(['originalid'], inplace=True...