Melting multiple groups of columns
When we needed to melt multiple groups of columns in the previous recipe, we used melt
twice and then merged the resulting DataFrames. That worked fine, but we can accomplish the same tasks in one step with the wide_to_long
function. wide_to_long
has more functionality than melt
, but is a bit more complicated to use.
Getting ready...
We will work with the weeks worked and college enrollment data from the NLS in this recipe.
How to do it…
We will transform multiple groups of columns at once using wide_to_long
:
- Import
pandas
and load the NLS data:>>> import pandas as pd >>> nls97 = pd.read_csv("data/nls97f.csv") >>> nls97.set_index('personid', inplace=True)
- View some of the weeks worked and college enrollment data:
>>> weeksworkedcols = ['weeksworked00','weeksworked01','weeksworked02', ... 'weeksworked03',&apos...