首页 文章

'Unsparsify'写入Excel时的pandas多索引

提问于
浏览
3

我有一个带有多索引的pandas数据帧,默认情况下,当打印到屏幕时,它会“稀疏”输出,以便不重复更高级别的索引 . 例如:

疏:

enter image description here

我可以将此更改为"unsparse",如下所示:
enter image description here

但是,df.to_excel(writer)不支持此选项,它将始终将索引编写为包含合并单元格的稀疏索引 . 有没有办法让这种写法以“非稀疏”的方式写入excel?或者我可以写入csv并将其导入excel,因为csv总是“非稀疏”,但这有点烦人 .

1 回答

  • 4

    在写入Excel之前尝试应用 reset_index() .

    一个例子 :

    first  second
    bar    one      -0.008620
           two       1.688653
    baz    one      -0.145099
           two       0.870981
    foo    one       2.544494
           two       0.935468
    qux    one      -1.868521
           two      -0.118242
    

    print(s.reset_index())

    first second         0
    0   bar    one -0.008620
    1   bar    two  1.688653
    2   baz    one -0.145099
    3   baz    two  0.870981
    4   foo    one  2.544494
    5   foo    two  0.935468
    6   qux    one -1.868521
    7   qux    two -0.118242
    

相关问题