Renaming axis levels for easy reshaping
Reshaping with the .stack
and .unstack
methods is far easier when each axis (both index and column) level has a name. pandas allows users to reference each axis level by integer location or by name. Since integer location is implicit and not explicit, you should consider using level names whenever possible. This advice follows from The Zen of Python (type import this
if you are not familiar with it), a short list of guiding principles for Python, of which the second one is "Explicit is better than implicit."
When grouping or aggregating with multiple columns, the resulting pandas object will have multiple levels in one or both of the axes. In this recipe, we will name each level of each axis and then use the .stack
and .unstack
methods to reshape the data to the desired form.
How to do it…
- Read in the college dataset, and find a few basic summary statistics on the undergraduate population and SAT math...