Official documents:
Pandas. Dataframe.unstack¶Dataframe. Unstack (Level=-1, fill_value=none) [source]¶
Pivot A level of the (necessarily hierarchical) index labels, returning a DATAFRAME has a new level of column labels WH OSE Inner-most level consists of the pivoted index labels. If The index is not a multiindex, the output would be a Series (the analogue's stack when the columns are not a multiindex (when there is only one row index, the result generates a series, which is detailed in the following example) the level involved'll automatically get sorted.
Parameters: |
Level: int, string, or List of the default-1 (last level) Level (s) of the index to Unstack, can pass level name fill_value : Replace NaN with this value if the unstack produces Missing values |
Returns: |
unstacked : Dataframe or Series |
Also dataframe.pivot pivot a table based on column values. Dataframe.stack Pivot A level of the column labels (inverse operation from Unstack).
Examples
>>> index = PD. Multiindex.from_tuples (' One ', ' a '), (' One ', ' B '),
... (' Two ', ' a '), (' Two ', ' B ')])
>>> s = PD. Series (Np.arange (1.0, 5.0), Index=index)
>>> s
one a 1.0
B 2.0 two A 3.0
B 4.0
Dtype:float64
>>> S.unstack (level=-1)
a b
one 1.0 2.0
Two 3.0 4.0
>>> S.unstack (level=0)
one two
a 1.0 3.0
B 2.0 4.0
>>> df = s.unstack (level=0)
>>> df.unstack ()
one a 1.0
B 2.0
Two a 3.0
B 4.0
Dtype:float64
The series returned here would have been: one two
a b a b
1 2 3 4
Such a dateframe, the same is to convert the row index to the column index, only so that the data is only one row, so automatically converted to series.