Pandas Series: unstack() function
Series-unstack() function
The unstack() function is used to reshape the data using stack() function in pandas converts the data into stacked format
The level involved will automatically get sorted.
Syntax:
Series.unstack(self, level=-1, fill_value=None)
| Name | Description | Type/Default Value | Required / Optional |
|---|---|---|---|
| level | Level(s) to unstack, can pass level name. | int, str, or list of these Default Value: Last Level |
Required |
| fill_value | Value to use when replacing NaN values. | scalar value Default Value: None |
Required |
Returns: DataFrame - Unstacked Series.
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4, 5],
index=pd.MultiIndex.from_product([['one', 'two'],
['x', 'y']]))
s
Output:
one x 2
y 3
two x 4
y 5
dtype: int64
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4, 5],
index=pd.MultiIndex.from_product([['one', 'two'],
['x', 'y']]))
s.unstack(level=-1)
Output:
x y
one 2 3
two 4 5
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4, 5],
index=pd.MultiIndex.from_product([['one', 'two'],
['x', 'y']]))
s.unstack(level=0)
Output:
one two
x 2 4
y 3 5
Previous: Sorts Pandas series by labels along the given axis
Next: Explode list-likes including lists, tuples, Series, and np.ndarray
