How to change multi-index to flat column names
I have this dataframe:
import pandas as pd
df = pd.DataFrame(data={'Status' : ['green','green','red','blue','red','yellow','black'],
'Group' : ['A','A','B','C','A','B','C'],
'City' : ['Toronto','Montreal','Vancouver','Toronto','Edmonton','Winnipeg','Windsor'],
'Sales' : [13,6,16,8,4,3,1]})
df.drop('Status',axis=1,inplace=True)
ndf = pd.pivot_table(df,values=['Sales'],index=['City'],columns=['Group'],fill_value=0,margins=False)
It looks like this:
In [321]: ndf
Out[321]:
Sales
Group A B C
City
Edmonton 4 0 0
Montreal 6 0 0
Toronto 13 0 8
Vancouver 0 16 0
Windsor 0 0 1
Winnipeg 0 3 0
How can I flatten it to become a simple dataframe:
City A B C
Edmonton 4 0 0
Montreal 6 0 0
Toronto 13 0 8
Vancouver 0 16 0
Windsor 0 0 1
Winnipeg 0 3 0
+3
source to share
3 answers