1

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)
2
  • Are you generating an HTML or Excel file? Commented Mar 20, 2017 at 11:44
  • I have parsed XML file, find the difference between attribute value, then transform into pandas dataframe and now I need highlight that cells with difference to make it easier to find it in excel, if there is no difference, do nothing. Commented Mar 20, 2017 at 11:49

2 Answers 2

3

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

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()

This generates the following Excel:

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

But I have 201 rows and 2105 columns. @DeepSpace
@jovicbg See my updated answer for a generalized solution. The number of rows doesn't matter.
Just deleted my row names, there is no that first column in excel
2

you can do it this way:

notnull_color = 'yellow'
df.style.applymap(lambda x: 'background-color: %s' % notnull_color if pd.notnull(x) else '')

1 Comment

This actually work, but I can't save it to excel. It's disapeared after running in new jupyter cell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.