在写入Excel时,“解析”一个pandas多索引

问题描述 投票:3回答:2

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

疏:

enter image description here

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

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

python excel pandas
2个回答
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

打印(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

0
投票

现在你可以指定merge_cells=False

一个例子:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]

df=pd.DataFrame(np.random.randn(8, 4), index=arrays)

df.to_excel('example.xlsx',merge_cells=False)
© www.soinside.com 2019 - 2024. All rights reserved.