使用“to_excel”保存时,为什么pandas数据帧样式会丢失?

问题描述 投票:1回答:1

根据this exampleto_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 openpyxl styling xlsxwriter
1个回答
0
投票

我自己偶然发现了这一点,据我所知,目前还没有像这样出口到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")

请注意,在高亮显示功能中,我会根据您在上面的列表推导中应用的条件创建一个布尔数据帧。然后我根据此数据帧的结果分配样式。

© www.soinside.com 2019 - 2024. All rights reserved.