Skip to content

CLN: Styler simplify existing builtin methods #39797

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

Merged
merged 4 commits into from
Feb 16, 2021
Merged
Changes from 3 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
136 changes: 70 additions & 66 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -1296,33 +1296,6 @@ def hide_columns(self, subset) -> Styler:
# A collection of "builtin" styles
# -----------------------------------------------------------------------

@staticmethod
def _highlight_null(v, null_color: str) -> str:
return f"background-color: {null_color}" if pd.isna(v) else ""

def highlight_null(
self,
null_color: str = "red",
subset: Optional[IndexLabel] = None,
) -> Styler:
"""
Shade the background ``null_color`` for missing values.

Parameters
----------
null_color : str, default 'red'
subset : label or list of labels, default None
A valid slice for ``data`` to limit the style application to.

.. versionadded:: 1.1.0

Returns
-------
self : Styler
"""
self.applymap(self._highlight_null, null_color=null_color, subset=subset)
return self

def background_gradient(
self,
cmap="PuBu",
Expand Down Expand Up @@ -1638,8 +1611,39 @@ def bar(

return self

def highlight_null(
self,
null_color: str = "red",
subset: Optional[IndexLabel] = None,
) -> Styler:
"""
Shade the background ``null_color`` for missing values.

Parameters
----------
null_color : str, default 'red'
subset : label or list of labels, default None
A valid slice for ``data`` to limit the style application to.

.. versionadded:: 1.1.0

Returns
-------
self : Styler
"""
return self.apply(
_Builtins._highlight_func,
axis=None,
subset=subset,
props=f"background-color: {null_color};",
highlight="null",
)

def highlight_max(
self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
self,
subset: Optional[IndexLabel] = None,
color: str = "yellow",
axis: Optional[Axis] = 0,
) -> Styler:
"""
Highlight the maximum by shading the background.
Expand All @@ -1658,10 +1662,19 @@ def highlight_max(
-------
self : Styler
"""
return self._highlight_handler(subset=subset, color=color, axis=axis, max_=True)
return self.apply(
_Builtins._highlight_func,
axis=axis,
subset=subset,
props=f"background-color: {color};",
highlight="max",
)

def highlight_min(
self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
self,
subset: Optional[IndexLabel] = None,
color: str = "yellow",
axis: Optional[Axis] = 0,
) -> Styler:
"""
Highlight the minimum by shading the background.
Expand All @@ -1680,43 +1693,13 @@ def highlight_min(
-------
self : Styler
"""
return self._highlight_handler(
subset=subset, color=color, axis=axis, max_=False
)

def _highlight_handler(
self,
subset=None,
color: str = "yellow",
axis: Optional[Axis] = None,
max_: bool = True,
) -> Styler:
subset = non_reducing_slice(maybe_numeric_slice(self.data, subset))
self.apply(
self._highlight_extrema, color=color, axis=axis, subset=subset, max_=max_
return self.apply(
_Builtins._highlight_func,
axis=axis,
subset=subset,
props=f"background-color: {color};",
highlight="min",
)
return self

@staticmethod
def _highlight_extrema(
data: FrameOrSeries, color: str = "yellow", max_: bool = True
):
"""
Highlight the min or max in a Series or DataFrame.
"""
attr = f"background-color: {color}"

if max_:
extrema = data == np.nanmax(data.to_numpy())
else:
extrema = data == np.nanmin(data.to_numpy())

if data.ndim == 1: # Series from .apply
return [attr if v else "" for v in extrema]
else: # DataFrame from .tee
return pd.DataFrame(
np.where(extrema, attr, ""), index=data.index, columns=data.columns
)

@classmethod
def from_custom_template(cls, searchpath, name):
Expand Down Expand Up @@ -1820,6 +1803,27 @@ def pipe(self, func: Callable, *args, **kwargs):
return com.pipe(self, func, *args, **kwargs)


class _Builtins:
@staticmethod
def _highlight_func(
data: FrameOrSeries,
props: str = "background-color: yellow;",
highlight: str = "max",
**kwargs,
) -> np.ndarray:
"""
Highlight the value in a Series or DataFrame by func with css-properties
"""
if highlight == "max":
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is extra complicated. just inline the conditionals in the functions themselvs.

return np.where(data == np.nanmax(data.values), props, "")
elif highlight == "min":
return np.where(data == np.nanmin(data.values), props, "")
elif highlight == "null":
return np.where(pd.isna(data).values, props, "")
else:
raise ValueError("'highlight' must one of 'max', 'min', 'null'")


class _Tooltips:
"""
An extension to ``Styler`` that allows for and manipulates tooltips on hover
Expand Down