Inverting stacked data
DataFrames have two similar methods, .stack and .melt, to convert horizontal column names into vertical column values. DataFrames can invert these two operations with the .unstack and .pivot methods, respectively. .stack and .unstack are methods that allow control over only the column and row indexes, while .melt and .pivot give more flexibility to choose which columns are reshaped.
In this recipe, we will call .stack and .melt on a dataset and promptly invert the operation with the .unstack and .pivot methods.
How to do it…
- Read in the college dataset with the institution name as the index, and with only the undergraduate race columns:
>>> def usecol_func(name): ... return 'UGDS_' in name or name == 'INSTNM' >>> college = pd.read_csv('data/college.csv', ... index_col='INSTNM', ... usecols=usecol_func) >>> college UGDS_WHITE UGDS_BLACK...