Python 3.x 读取多索引excel文件,并重塑文件中的标题

Python 3.x 读取多索引excel文件,并重塑文件中的标题,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,给定excel文件data.xlsx,如下所示: 我用df=pd.read\u excel('data.xlsx',header=[0,1],index\u col=[0,1],sheet\u name='Sheet1')阅读了它 输出: 我想知道是否可以将其转换为以下格式?谢谢你的帮助 与和一起使用: 非常感谢。我读的excel正确吗?似乎缺少city。您可以检查pd.read\u excel('data.xlsx',header=[0,1],index\u col=[0,1],sheet\

给定excel文件
data.xlsx
,如下所示:

我用
df=pd.read\u excel('data.xlsx',header=[0,1],index\u col=[0,1],sheet\u name='Sheet1')阅读了它

输出:

我想知道是否可以将其转换为以下格式?谢谢你的帮助

与和一起使用:


非常感谢。我读的excel正确吗?似乎缺少
city
。您可以检查
pd.read\u excel('data.xlsx',header=[0,1],index\u col=[0,1],sheet\u name='Sheet1')的输出。
问题中没有列名
city
@ahbon-我知道,这是类似于列的元数据的唯一名称。所以,如果不在输入文件中,则无法解析。所以在我的解决方案中,使用了
rename\u axis
来设置它。@ahbon-效果如何?谢谢,我将用它进行测试。
district  2018        2019      
         price ratio price ratio
bj cy       12  0.01     6  0.02
sh hp        4  0.02     3  0.05
df = df.stack(0).rename_axis(('city','district','year')).reset_index()
print (df)
  city district  year  price  ratio
0   bj       cy  2018     12   0.01
1   bj       cy  2019      6   0.02
2   sh       hp  2018      4   0.02
3   sh       hp  2019      3   0.05