Skip to content
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

PERF: make Styler default formatter arguments statics instead of repeated dynamic #40425

Merged
merged 4 commits into from
Mar 14, 2021
Merged
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ Deprecations
- Deprecated :meth:`core.window.ewm.ExponentialMovingWindow.vol` (:issue:`39220`)
- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`)
- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like; will raise if any function fails on a column in a future version (:issue:`40211`)

.. ---------------------------------------------------------------------------
Expand Down
10 changes: 5 additions & 5 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,10 @@ def __init__(
self.cell_context: Dict[str, Any] = {}
self._todo: List[Tuple[Callable, Tuple, Dict]] = []
self.tooltips: Optional[_Tooltips] = None
def_precision = get_option("display.precision")
self._display_funcs: DefaultDict[ # maps (row, col) -> formatting function
Tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: partial(_default_formatter, precision=None))
] = defaultdict(lambda: partial(_default_formatter, precision=def_precision))
self.precision = precision # can be removed on set_precision depr cycle
self.na_rep = na_rep # can be removed on set_na_rep depr cycle
self.format(formatter=None, precision=precision, na_rep=na_rep)
Expand Down Expand Up @@ -2127,24 +2128,22 @@ def _get_level_lengths(index, hidden_elements=None):
return non_zero_lengths


def _default_formatter(x: Any, precision: Optional[int] = None) -> Any:
def _default_formatter(x: Any, precision: int) -> Any:
"""
Format the display of a value

Parameters
----------
x : Any
Input variable to be formatted
precision : Int, optional
precision : Int
Floating point precision used if ``x`` is float or complex.

Returns
-------
value : Any
Matches input type, or string if input is float or complex.
"""
if precision is None:
precision = get_option("display.precision")
if isinstance(x, (float, complex)):
return f"{x:.{precision}f}"
return x
Expand All @@ -2165,6 +2164,7 @@ def _maybe_wrap_formatter(
elif callable(formatter):
formatter_func = formatter
elif formatter is None:
precision = get_option("display.precision") if precision is None else precision
formatter_func = partial(_default_formatter, precision=precision)
else:
raise TypeError(f"'formatter' expected str or callable, got {type(formatter)}")
Expand Down