【问题标题】:why pandas dataframe style lost when saved with "to_excel"?为什么使用“to_excel”保存时熊猫数据框样式丢失?
【发布时间】:2019-03-18 19:53:58
【问题描述】:

根据this example to_excel 方法应该使用背景颜色保存 Excel 文件。但是,我保存的 Excel 文件中没有任何颜色。 我尝试使用 openpyxlxlsxwriter 引擎进行编写。在这两种情况下,Excel 文件都已保存,但单元格颜色/样式丢失了。

我可以用openpyxl读回文件并重新格式化,但是如果这个to_excel方法应该工作,为什么不呢?

这里是示例代码。

 import pandas as pd # version 0.24.2
 dict = {'A': [1, 1, 1, 1, 1], 'B':[2, 1, 2, 1, 2], 'C':[1, 2, 1, 2, 1]}
 df = pd.DataFrame(dict)
 df_styled = df.style.apply(lambda x: ["background: #ffa31a" if x.iloc[0] < v else " " for v in x], axis=1)

 df_styled 
 ''' in my jupyter notebook, this displayed my dataframe with background color when condition is met, (all the 2s highlighted)'''

 '''Save the styled data frame to excel using to_excel'''
 df_styled.to_excel('example_file_openpyxl.xlsx', engine='openpyxl')
 df_styled.to_excel('example_file_xlsxwriter.xlsx', engine='xlsxwriter')

【问题讨论】:

  • 您使用的是什么版本的 Pandas?
  • 我正在使用“0.24.2”。谢谢!
  • 就个人而言,我建议您将数据框转换为行并在 openpyxl 或 xlsxwriter 中手动应用您想要的任何样式。
  • @Charlie Clark,用 pandas 设计 df 似乎是一种更简单的方法,主要是因为我以前从未使用过 openpyxl 或 xlxswriter。我现在开始为此学习openpyxl,我认为这也很好。我主要是好奇我是否遗漏了一些东西/或者在使用 pandas 的 df 样式和保存方面做错了什么。文档中的示例似乎有效。还想知道,如果您使用提供的代码得到与我相同的结果?
  • 在第四行中,尝试将 background 更改为 background-color。这为我解决了同样的问题。

标签: pandas openpyxl xlsxwriter pandas-styles


【解决方案1】:

我自己偶然发现了这一点,据我所知,尚不支持像这样导出到 excel。我已调整您的代码以匹配文档中的 excel 输出。

这是输出到excel方法的文档。

df.style.\
    applymap(color_negative_red).\
    apply(highlight_max).\
    to_excel('styled.xlsx', engine='openpyxl')

这是你的代码调整:

import pandas as pd
dict = {'A': [1, 1, 1, 1, 1], 'B':[2,1,2,1,2], 'C':[1,2,1,2,1]}
df = pd.DataFrame(dict)

def highlight(df, color = "yellow"):

    attr = 'background-color: {}'.format(color)
    df_bool = pd.DataFrame(df.apply(lambda x: [True if x.iloc[0] < v else False for v in x],axis=1).apply(pd.Series),
                      index=df.index)
    df_bool.columns =df.columns
    return pd.DataFrame(np.where(df_bool, attr, ""),
                       index= df.index, columns=df.columns)
df.style. \
    apply(highlight, axis=None).\
    to_excel("styled.xlsx", engine="openpyxl")

在高亮函数中,我根据上面列表理解中应用的条件创建了一个布尔数据框。然后,我根据这个数据框的结果分配样式。

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 2020-08-03
    • 2017-11-09
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多