我有这个数据框:
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)
看起来像这样:
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
我怎样才能把它展平成简单的数据框:
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
最佳答案
ndf = ndf.Sales.reset_index()
ndf
Out[4]:
Group City A B C
0 Edmonton 4 0 0
1 Montreal 6 0 0
2 Toronto 13 0 8
3 Vancouver 0 16 0
4 Windsor 0 0 1
5 Winnipeg 0 3 0
关于python - 如何将多索引更改为平面列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30906452/