我有这个数据框:
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
答案 0 :(得分:2)
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
答案 1 :(得分:1)
从列索引中删除一个级别,然后删除名称:
In [94]: ndf.columns = ndf.columns.droplevel()
In [95]: ndf.columns.name=None
In [96]: ndf
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
答案 2 :(得分:0)
您需要按如下方式重置列:
ndf.columns = ndf.columns.droplevel()
>>> ndf
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