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.
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.