首页 > 解决方案 > 在 Python 中使用 MultiIndex 和 to_excel 时创建的标题下方的空行

问题描述

我正在尝试使用带有 XlsxWriter 的 to_excel 函数将 Pandas 数据框保存到 excel 文件中。

当我将数据帧打印到终端时,它会按原样读取,但是当我将其保存到 excel 并打开文件时,标题下方有一个额外的空白行,不应该存在。这仅在将 MultiIndex 用于标头时发生,但我需要它提供的分层标头,但我找不到解决方案。

下面是来自在线 MultiIndex 示例的代码,它产生的结果与我正在处理的项目相同。任何解决方案将不胜感激。

import numpy as np
import pandas as pd
import xlsxwriter

tuples = [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')]

index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

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

pd.MultiIndex.from_product(iterables, names=['first', 'second'])

df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)

print(df)

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='test1')

创建的 excel 输出: 在此处输入图像描述

标签: pythonpandasmulti-indexxlsxwriter

解决方案


非常感谢这个问题和@Teoretic 的解决方法。

但是,在我的情况下,列的合并单元格Multiindex非常有用,而@Teoretic 则丢失了这些单元格。我已经完成了另一种解决方法,在编写之前隐藏了整行,它可以工作,因此我将它包含在此处以防万一对任何人有用。

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='test1')
writer.sheets['test1'].set_row(2, None, None, {'hidden': True})
writer.save()

推荐阅读