Pandas: Stack a DataFrame, Unstack a Series

19 August 2020

Code

# Import libraries
import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'fan':['table_fan', 'table_fan', 'table_fan', 'floor_fan', 'floor_fan', 'floor_fan'],
    'type': ['swivel', 'oscillate', 'static','swivel', 'oscillate', 'static'],
    'degree': [181, 272, 0, 186, 275, .5],
    'count': [35,12,34,56,76,66]
    }
)

print(df)

DataFrame to be stacked:

         fan       type  degree  count
0  table_fan     swivel   181.0     35
1  table_fan  oscillate   272.0     12
2  table_fan     static     0.0     34
3  floor_fan     swivel   186.0     56
4  floor_fan  oscillate   275.0     76
5  floor_fan     static     0.5     66

Stack:

# Stack DataFrame to Series
stacked = df.stack(level=0)

# Output
print("Stacked Series: \n", stacked)
print(type(stacked))

Output: # 1

Stacked Series:  
 0  fan       table_fan
   type         swivel
   degree          181
   count            35
1  fan       table_fan
   type      oscillate
   degree          272
   count            12
2  fan       table_fan
   type         static
   degree            0
   count            34
3  fan       floor_fan
   type         swivel
   degree          186
   count            56
4  fan       floor_fan
   type      oscillate
   degree          275
   count            76
5  fan       floor_fan
   type         static
   degree          0.5
   count            66
dtype: object
<class 'pandas.core.series.Series'>

Unstack

# Unstack a Series to DatFrame
unstacked = stacked.unstack(level=1)

# Output
print("Unstacked Series: \n", unstacked)
print(type(unstacked))

Output: # 2

Unstacked Series: 
          fan       type degree count
0  table_fan     swivel    181    35
1  table_fan  oscillate    272    12
2  table_fan     static      0    34
3  floor_fan     swivel    186    56
4  floor_fan  oscillate    275    76
5  floor_fan     static    0.5    66
<class 'pandas.core.frame.DataFrame'>






Any errors in code above?
Please send a message.