Renaming axis levels for easy reshaping
Reshaping with the stack
/unstack
methods is far easier when each axis (index/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 TheZen of Python (http://bit.ly/2xE83uC), a short list of guiding principles for Python of which the second one is Explicit is better than implicit.
Getting ready
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 methods stack
/unstack
to dramatically 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 scores by institution and religious affiliation:
>>> college = pd...