- API reference
- DataFrame
- pandas.DataF...
pandas.DataFrame.unstack#
- DataFrame.unstack(level=-1,fill_value=None,sort=True)[source]#
Pivot a level of the (necessarily hierarchical) index labels.
Returns a DataFrame having a new level of column labels whose inner-most levelconsists of the pivoted index labels.
If the index is not a MultiIndex, the output will be a Series(the analogue of stack when the columns are not a MultiIndex).
- Parameters:
- levelint, str, or list of these, default -1 (last level)
Level(s) of index to unstack, can pass level name.
- fill_valueint, str or dict
Replace NaN with this value if the unstack produces missing values.
- sortbool, default True
Sort the level(s) in the resulting MultiIndex columns.
- Returns:
- Series or DataFrame
See also
DataFrame.pivot
Pivot a table based on column values.
DataFrame.stack
Pivot a level of the column labels (inverse operation fromunstack).
Notes
Referencethe user guide for more examples.
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)>>>sone a 1.0 b 2.0two a 3.0 b 4.0dtype: float64
>>>s.unstack(level=-1) a bone 1.0 2.0two 3.0 4.0
>>>s.unstack(level=0) one twoa 1.0 3.0b 2.0 4.0
>>>df=s.unstack(level=0)>>>df.unstack()one a 1.0 b 2.0two a 3.0 b 4.0dtype: float64
On this page