且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pandas 数据框中的颜色单元格

更新时间:2022-06-03 23:04:26

据我所知,df.style仅在将数据框导出为HTML时使用.

As far as I know, df.style is only used when exporting the dataframe to HTML.

对于Excel,如果我建议使用编写的库,请参见以下示例代码(请注意,由于使用整数作为标题存在一个小问题,因此此列标题使用了字符串):

For Excel, If I may suggest using a library that I wrote, see this example code (Note that this is using strings for the column headers since there is a small issue with using integers as headers):

import pandas as pd
from StyleFrame import StyleFrame, Styler

df = pd.DataFrame({'1': [None, None, 33, None],
                   '2': [23, None, None, None],
                   '3': [None, 54, None, 24]})

sf = StyleFrame(df)
style = Styler(bg_color='yellow')
for col_name in df.columns:
    sf.apply_style_by_indexes(sf[~df[col_name].isnull()], cols_to_style=col_name,
                              styler_obj=style)
sf.to_excel('test.xlsx').save()

这将生成以下Excel:

This generates the following Excel: