【问题标题】:Avoid merged cells in pandas to_excel method避免在 pandas to_excel 方法中合并单元格
【发布时间】:2018-03-17 22:46:55
【问题描述】:

我有一个多索引数据框,我必须将其保存为 Excel 文件。当我使用 pandas 方法“to_excel”来执行此操作时,我得到了一个包含合并单元格的漂亮表格。以下是此类表格的示例:

不幸的是,在 excel 中过滤该表的第一列是非常有问题的,因为 excel 不理解合并的单元格属于一起: https://www.extendoffice.com/documents/excel/1955-excel-filter-merged-cells.html

这就是为什么我需要 'to_excel' 方法来保存这样的数据框:

这可能吗?

顺便说一下,这是我用来生成第一个表的代码:

df = pd.DataFrame({"animal": ("horse", "horse", "dog", "dog"), "color of fur": ("black", "white", "grey", "black"), "name": ("Blacky", "Wendy", "Rufus", "Catchy")})

mydf = df.set_index(["animal", "color of fur"])

mydf.to_excel("some_path_here")

【问题讨论】:

  • 您需要多索引吗?如果只是从索引创建列 - mydf = mydf.reset_index() 那么一切都很好......
  • 原则上你是对的,但是 muliindex 的优点是列是粗体的。但是舒尔,我可以忍受。谢谢!

标签: python pandas


【解决方案1】:

使用merge_cells=False参数:

mydf.to_excel("some_path_here", merge_cells=False)

来自docs

merge_cells:布尔值,默认为 True

将 MultiIndex 和 Hierarchical Rows 写入合并单元格。

【讨论】:

    【解决方案2】:

    另一种可能性是使用xlwings(需要安装excel)将数据框插入excel,缺点是索引和列没有格式化,所以MaxU的答案是优越的。

    import xlwings as xw
    import pandas as pd
    
    df = pd.DataFrame({"animal": ("horse", "horse", "dog", "dog"), "color of fur": ("black", "white", "grey", "black"), "name": ("Blacky", "Wendy", "Rufus", "Catchy")}).set_index(["animal", "color of fur"])
    
    with xw.App(visible=False) as app:
        wb = xw.Book()
        wb.sheets[0].range("A1").value = df
        wb.save(r"test.xlsx")
        wb.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      相关资源
      最近更新 更多