What do stacking and unstacking mean from a mathematical point of view? First one has to understand what it means to represent data in a data frame.
I like to think of a column of a data frame as a function.
I am going to assume that all the columns are of the same type. In my notation, I will assume that the “innermost index” is last.
A dataframe thus represents a function of type \[ (\ldots,S_1, S_0) \to (\ldots,X_1, X_0) \to Y \] This means that the index (row) are given by \(\ldots,S_1,S_0\), and the column indices are \(\ldots,X_1,X_0\).
The operation of stacking is the transformation to the type: \[ (\ldots,S_1, S_0, X_0) \to (\ldots,X_1) \to Y \] This operation makes the dataframe taller.
The operation of unstacking is the reverse transformation, namely: \[ (\ldots,S_1) \to (\ldots, X_1, X_0, S_0) \to Y \] This operation makes the dataframe wider.