You are viewing documentation about an older version (1.23.0). View latest version

modin.pandas.DataFrame.unstack¶

DataFrame.unstack(level: int | str | list = - 1, fill_value: int | str | dict = None, sort: bool = True)[source]¶

Pivot a level of the (necessarily hierarchical) index labels.

Returns a DataFrame having a new level of column labels whose inner-most level consists 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:
  • level (int, str, list, default -1) – Level(s) of index to unstack, can pass level name.

  • fillna (int, str, dict, optional) – Replace NaN with this value if the unstack produces missing values.

  • sort (bool, default True) – Sort the level(s) in the resulting MultiIndex columns.

Return type:

Series or DataFrame

Notes

Supports only integer level and sort = True. Internally, calls pivot_table or melt to perform unstack operation.

See also

DataFrame.pivot

Pivot without aggregation that can handle non-numeric data.

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
Copy