How to add second level indices to a pandas dataframe

Viewed 23

I have the following dataframe:

 d={'col1':{('a','aaa'):1,
          ('a','bbb'):2,
          ('b','bbb'):1,
          ('b','ccc'):2} }
 df=pd.DataFrame(d)

I want to change the dataframe, so that it will have all 'aaa', 'bbb', 'ccc' 2nd level indices for both 'a' and 'b' 1st level indices.

1 Answers

You can try unstack with stack

df = df.unstack().stack(dropna=False)
Out[82]: 
       col1
a aaa   1.0
  bbb   2.0
  ccc   NaN
b aaa   NaN
  bbb   1.0
  ccc   2.0
Related