python-3.x - 读取多索引 Excel 文件并 reshape Pandas 中的标题

标签 python-3.x pandas dataframe

给定一个 Excel 文件 data.xlsx如下:

enter image description here

我已经用 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

请问是否可以将其转换为以下格式?感谢您的帮助。

enter image description here

最佳答案

使用DataFrame.stackDataFrame.rename_axisDataFrame.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/

相关文章:

python - 在Python中循环运行多个数据帧的回归

python - 从列表格式的数据框列中删除重复项

python - 在 python 中设置 pandas 数据框的样式使得浮点值在小数点后有更多的零

python - Pandas :时间戳到日期时间

r - 融化数据框, reshape 高大的数据框

python - PyQt4 python 中的 "RuntimeError: maximum recursion depth exceeded while calling a Python object"错误

python-3.x - 如何在 Windows 10 中的 anaconda 发行版上安装 tflearn 模块

python - Pandas drop 函数在 for 循环中不起作用?

python - 基于列 pandas 保留特定类型的行

R 按组识别数据帧更改模式