Data analysts must possess the ability and tools to look at data from different layouts and orientations in order to draw solid insights.
To begin with, let us define the ‘shape’ of a data set. The shape of a data set refers to the way in which a data set is arranged into rows and columns, and reshaping data is the rearrangement of the data without altering the content of the data set. Reshaping data sets is a very frequent and cumbersome task in the process of data manipulation and analysis. Data analysts must possess the ability and tools to look at data from different layouts and orientations in order to draw solid insights.
Reshaping data sets in Python
Python offers multiple functions to reshape data sets and so let’s explore two of these.
stack(): reshapes the DataFrame by converting the data into stacked form, that means pivoting the innermost column index into the innermost row index.
You can reshape a stacked DataFrame back to its unstacked format with the unstack() function.
Try this code:
Code:
data=data_stack.unstack()data
Output:
By default, the innermost level is unstacked. In our example, it was a number. However, you can unstack a different level by passing a level number or name as a parameter to the unstack() method.
For example, try this code that unstacks data_stack at the level of state, rather than number: