Import NumPy as NP
import pandas as PD
Stack
Rotate the row index to a column index and complete the hierarchy index.
In the following example, first create a box of 5x2 dataframe.
It is then stack, so the original row index becomes the outer index, and the original column index becomes an inner index.
Df_obj = PD. Dataframe (Np.random.randint (0,10, (5,2)), columns=[' data1 ', ' data2 '])
print Df_obj
Data1 data2
0 9 0
1 7 4 2 6 1 3 2 7 4 9 1
Stacked = Df_obj.stack ()
print stacked
0 data1 9
data2 0
1 data1 7
data2 4
2 data1 6
data2 1
3 data1 2
data2 7
4 data1 9
data2 1
Dtype:int64
The type of data after the refactoring was printed and found to have been transformed from Dataframe to series type.
Prints the type of index of the new data, discovering that the format of the indexes has become a multi-tiered index.
Print type (stacked)
print type (stacked.index)
<class ' pandas.core.series.Series ' >
<class ' pandas.indexes.multi.MultiIndex ' >
Unstack
Unstack the default series of multi-tier indexes into Dataframe, which by default is an internal index that is about to be converted to dataframe column indexes.
You can also specify the index level of the operation. Lavel=0 represents the Operation outer Index.
# Default Action inner-layer index
print stacked.unstack ()
Data1 data2
0 9 0
1 7 4 2 6 1 3 2 7 4 9 1
# Specify the level of the action index through levels
print Stacked.unstack (level=0)
0 1 2 3 4
data1 9 7 6 2 9
data2 0 4 1 7 1
Note: Some examples come from the Little Elephant College Robin course