如何设置Pandas DataFrame左上角单元格的样式?
设置DataFrame左上角单元格样式并导出Excel保留样式
初始问题
我知道可以用df.columns.name访问DataFrame的左上角单元格,也了解Pandas样式功能里的apply_index能设置行/列标题样式,但不知道怎么给这个左上角单元格设置样式(比如把背景改成蓝色)。
导出时的问题
按照方法设置好样式后,用to_excel()把Styler对象导出到Excel时,左上角单元格的样式无法保留。查Pandas导出至Excel章节的文档说明:
表格级样式和数据单元格CSS类不会被包含在Excel导出中:单个单元格的属性必须通过
Styler.apply和/或Styler.applymap方法映射
可行解决方案
感谢ouroboros1的帮助,以下是能实现需求的代码示例,可完成DataFrame样式设置并导出到Excel,最终效果如图:
步骤1:创建带列名的DataFrame
import pandas as pd d = {'col1': [1, 2], 'col2': [3, 4]} df = pd.DataFrame(data=d) df.columns.name = 'Test' df
步骤2:完整样式设置与导出代码
import pandas as pd d = {'col1': [1, 2], 'col2': [3, 4]} # 定义数据单元格的样式矩阵 color_matrix_df = pd.DataFrame([['background-color:yellow', 'background-color:yellow'], ['background-color:yellow', 'background-color:blue']]) df = pd.DataFrame(data=d) df.columns.name = 'Test' # 应用数据单元格样式的函数 def colors(df, color_matrix_df): style_df = pd.DataFrame(color_matrix_df.values, index=df.index, columns=df.columns) return style_df.applymap(lambda elem: elem) # 设置左上角单元格的前端展示样式 df_upper_left_cell = df.style.set_table_styles( [{'selector': '.index_name', 'props': [('background-color', 'IndianRed'), ('color', 'white')] }] ) # 给数据单元格应用样式 df_upper_left_cell.apply(colors, axis=None, color_matrix_df=color_matrix_df) # 导出到Excel,并通过xlsxwriter手动设置左上角单元格样式 w = pd.ExcelWriter('Test.xlsx', engine='xlsxwriter') df_upper_left_cell.to_excel(w, index=True) wb = w.book ws = w.sheets['Sheet1'] # 定义左上角单元格的格式 fmt_header = wb.add_format({'fg_color': '#cd5c5c', 'align': 'center'}) # 写入左上角单元格内容并应用格式 ws.write(0,0, df_upper_left_cell.data.columns.name, fmt_header) w.save()
最终效果

内容的提问来源于stack exchange,提问作者Chenyang
相关产品推荐
相关产品推荐

