diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 13f7a3dbe7d4a..e5e1dac73f070 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -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 @@ -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, diff --git a/pandas/core/format.py b/pandas/core/format.py index 2355ae16874ce..158a2975f77fe 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -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): @@ -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 @@ -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): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b485d51514162..9165fbfa96083 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -485,9 +485,10 @@ def _repr_html_(self): ignore_width=ipnbh) if fits_horizontal and fits_vertical: + hn = get_option("display.highlight_nan") return ('