diff --git a/pandas/core/style.py b/pandas/core/style.py index 76460fdf224b2..f66ac7485c76e 100644 --- a/pandas/core/style.py +++ b/pandas/core/style.py @@ -7,8 +7,7 @@ from contextlib import contextmanager from uuid import uuid1 import copy -from collections import defaultdict -from collections.abc import MutableMapping +from collections import defaultdict, MutableMapping try: from jinja2 import Template @@ -273,7 +272,7 @@ def _translate(self): caption=caption, table_attributes=self.table_attributes) def format(self, formatter, subset=None): - ''' + """ Format the text display value of cells. .. versionadded:: 0.18.0 @@ -282,6 +281,8 @@ def format(self, formatter, subset=None): ---------- formatter: str, callable, or dict subset: IndexSlice + An argument to ``DataFrame.loc`` that restricts which elements + ``formatter`` is applied to. Returns ------- @@ -292,8 +293,9 @@ def format(self, formatter, subset=None): ``formatter`` is either an ``a`` or a dict ``{column name: a}`` where ``a`` is one of - - str: this will be wrapped in: ``a.format(x)`` - - callable: called with the value of an individual cell + + - str: this will be wrapped in: ``a.format(x)`` + - callable: called with the value of an individual cell The default display value for numeric values is the "general" (``g``) format with ``pd.options.display.precision`` precision. @@ -305,7 +307,7 @@ def format(self, formatter, subset=None): >>> df.style.format("{:.2%}") >>> df['c'] = ['a', 'b', 'c', 'd'] >>> df.style.format({'C': str.upper}) - ''' + """ if subset is None: row_locs = range(len(self.data)) col_locs = range(len(self.data.columns)) @@ -853,11 +855,11 @@ def _highlight_extrema(data, color='yellow', max_=True): def _maybe_wrap_formatter(formatter): - if not (callable(formatter) or com.is_string_like(formatter)): + if com.is_string_like(formatter): + return lambda x: formatter.format(x) + elif callable(formatter): + return formatter + else: msg = "Expected a template string or callable, got {} instead".format( formatter) raise TypeError(msg) - if not callable(formatter): - return lambda x: formatter.format(x) - else: - return formatter diff --git a/pandas/tests/test_style.py b/pandas/tests/test_style.py index fb008c2d9a6f5..bfabaab8ad2f5 100644 --- a/pandas/tests/test_style.py +++ b/pandas/tests/test_style.py @@ -17,9 +17,12 @@ if job_name == '27_slow_nnet_LOCALE': raise SkipTest("No jinja") try: - from pandas.core.style import Styler + # Do try except on just jinja, so the only reason + # We skip is if jinja can't import, not something else + import jinja2 # noqa except ImportError: raise SkipTest("No Jinja2") +from pandas.core.style import Styler # noqa class TestStyler(TestCase):