HappyPy HappyPy - 13 days ago 7
Python Question

how to simplify dataframe with multiple indexes using pandas?

df = pd.DataFrame({'c1':[1,1,2,2,3,3,4,4], 'c2':['a','b','a','b','a','b','a','b'], 'c3':[25,34,12,14,91,31,52,15]})
df.set_index(['c1','c2'],inplace=True)
df2 = df.unstack('c2')


How can I modify
df2
to look like this?

c1 a b
1 25 34
2 12 14
3 91 31
4 52 15

Answer

You can drop the column level by renaming the columns:

df2.columns = df2.columns.droplevel(level = 0).values

enter image description here