gpt4 book ai didi

python - 如何将多索引更改为平面列名

转载 作者:行者123 更新时间:2023-11-28 16:32:01 26 4
gpt4 key购买 nike

我有这个数据框:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com