pandas 数据框中的颜色单元格 [英] Colour cells in pandas dataframe

查看:94
本文介绍了 pandas 数据框中的颜色单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有不同值的数据框,但是大多数tham是NaN(无).我想为值不是None的单元格着色,而值实际上是值. 例如:dataxml =

I have a dataframe with different values, but most of tham are NaN (None). I want to colour cells where value is not a None, where is actually value. For example: dataxml=

    1      2     3      4     5 
a  NaN    23    NaN   NaN    65
b  NaN    NaN    54   NaN   NaN
c   33    NaN   NaN   NaN   NaN
d  NaN    NaN    24   NaN   NaN

此代码为整个数据框上色:

This code color whole dataframe:

def highlight_cells(value):
    if value != None:
        return 'background-color: yellow'

dataxml.style.applymap(highlight_cells)

推荐答案

据我所知,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:

这篇关于 pandas 数据框中的颜色单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆