给定一个 Excel 文件 data.xlsx
如下:
我已经用 df = pd.read_excel('data.xlsx', header = [0, 1], index_col = [0, 1], sheet_name = 'Sheet1')
阅读过它,
输出:
district 2018 2019
price ratio price ratio
bj cy 12 0.01 6 0.02
sh hp 4 0.02 3 0.05
请问是否可以将其转换为以下格式?感谢您的帮助。
最佳答案
使用DataFrame.stack
与 DataFrame.rename_axis
和 DataFrame.reset_index
:
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
关于python-3.x - 读取多索引 Excel 文件并 reshape Pandas 中的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61381471/