python - 在 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')
解决方案
非常感谢这个问题和@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()
推荐阅读
- indexeddb - IndexedDb 文件位置可以是共享位置吗
- javascript - 使用 Javascript 在页面加载时设置 uuid
- python - 堆叠 Pandas 数据框
- getstream-io - 我可以阻止我的应用的非活跃用户更新动态吗?
- django - 如何使用 Azure 和 Django 在 SPA 上验证令牌上的签名?
- uwp - 使用 Fluent Design 的 UWP 导航
- android - 31.0.0 不是有效的 SDK 版本。选项是 26.0.0 未版本化
- javascript - 在 vue 中引用外部 json 文件
- node.js - 错误:模块@ionic-native/core/decorators.d.ts 的元数据版本不匹配
- python - Selenium:前两个完成后执行第三个函数