Skip to content

ENH: Add option to highlight NaN cells #5330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pandas/core/config_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,15 @@
Setting this to None/False restores the values to their initial value.
"""


pc_highlight_nan_doc = """
: bool

When True, NaN elements in the HTML represenation of Series or
DataFrames are displayed with a yellow background.

"""

style_backup = dict()
def mpl_style_cb(key):
import sys
Expand Down Expand Up @@ -245,6 +254,8 @@ def mpl_style_cb(key):
validator=is_instance_factory([type(None), int]))
# redirected to width, make defval identical
cf.register_option('line_width', get_default_val('display.width'), pc_line_width_doc)
cf.register_option('highlight_nan', False, pc_highlight_nan_doc,
validator=is_bool)

cf.deprecate_option('display.line_width',
msg=pc_line_width_deprecation_warning,
Expand Down
11 changes: 8 additions & 3 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -456,11 +456,12 @@ def _format_col(self, i):
na_rep=self.na_rep,
space=self.col_space)

def to_html(self, classes=None):
def to_html(self, classes=None, highlight_nan=False):
"""
Render a DataFrame to a html table.
"""
html_renderer = HTMLFormatter(self, classes=classes)
html_renderer = HTMLFormatter(self, classes=classes,
highlight_nan=highlight_nan)
if hasattr(self.buf, 'write'):
html_renderer.write_result(self.buf)
elif isinstance(self.buf, compat.string_types):
Expand Down Expand Up @@ -558,9 +559,10 @@ class HTMLFormatter(TableFormatter):

indent_delta = 2

def __init__(self, formatter, classes=None):
def __init__(self, formatter, classes=None, highlight_nan=False):
self.fmt = formatter
self.classes = classes
self.highlight_nan = highlight_nan

self.frame = self.fmt.frame
self.columns = formatter.columns
Expand All @@ -581,6 +583,9 @@ def write_th(self, s, indent=0, tags=None):
return self._write_cell(s, kind='th', indent=indent, tags=tags)

def write_td(self, s, indent=0, tags=None):
tags = (tags or "")
tags += ' style="background-color:yellow"' if \
self.highlight_nan and s == self.fmt.na_rep else ""
return self._write_cell(s, kind='td', indent=indent, tags=tags)

def _write_cell(self, s, kind='td', indent=0, tags=None):
Expand Down
9 changes: 6 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,9 +485,10 @@ def _repr_html_(self):
ignore_width=ipnbh)

if fits_horizontal and fits_vertical:
hn = get_option("display.highlight_nan")
return ('<div style="max-height:1000px;'
'max-width:1500px;overflow:auto;">\n' +
self.to_html() + '\n</div>')
self.to_html(highlight_nan=hn) + '\n</div>')
else:
buf = StringIO(u(""))
max_info_rows = get_option('display.max_info_rows')
Expand Down Expand Up @@ -1289,7 +1290,7 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
header=True, index=True, na_rep='NaN', formatters=None,
float_format=None, sparsify=None, index_names=True,
justify=None, force_unicode=None, bold_rows=True,
classes=None, escape=True):
classes=None, escape=True, highlight_nan=False):
"""
to_html-specific options

Expand All @@ -1299,6 +1300,8 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
CSS class(es) to apply to the resulting html table
escape : boolean, default True
Convert the characters <, >, and & to HTML-safe sequences.
highlight_nan: boolean, default False
Display NaN cells with yellow background

Render a DataFrame as an HTML table.
"""
Expand All @@ -1322,7 +1325,7 @@ def to_html(self, buf=None, columns=None, col_space=None, colSpace=None,
header=header, index=index,
bold_rows=bold_rows,
escape=escape)
formatter.to_html(classes=classes)
formatter.to_html(classes=classes, highlight_nan=highlight_nan)

if buf is None:
return formatter.buf.getvalue()
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1246,6 +1246,13 @@ def test_to_html_with_no_bold(self):
ashtml = x.to_html(bold_rows=False)
assert('<strong>' not in ashtml[ashtml.find('</thead>')])


def test_to_html_with_highlight_nan(self):
x = DataFrame({'c1': [1, 2], 'c2': [3, nan]})
ashtml = x.to_html(highlight_nan=True)
assert('style="background-color:yellow"' in ashtml)


def test_to_html_columns_arg(self):
result = self.frame.to_html(columns=['A'])
self.assert_('<th>B</th>' not in result)
Expand Down