Skip to content

Commit c42de40

Browse files
committed
Add built-in funcion for Styler to format the text displayed for missing values
As described in GH pandas-dev#28358, user who wants to control how NA values are printed while applying styles to the output will have to implement their own formatter. (so that the underlying data will not change and can be used for styling) Since the behavior is common in styling (for reports etc.), suggest to add this shortcut function to enable users format their NA values as something like '--' or 'Not Available' easily. example usage: `df.style.highlight_max().format_null('--')`
1 parent e623f0f commit c42de40

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

doc/source/whatsnew/v1.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ Other enhancements
110110
- :meth:`DataFrame.to_json` now accepts an ``indent`` integer argument to enable pretty printing of JSON output (:issue:`12004`)
111111
- :meth:`read_stata` can read Stata 119 dta files. (:issue:`28250`)
112112
- Added ``encoding`` argument to :func:`DataFrame.to_html` for non-ascii text (:issue:`28663`)
113+
- :meth:`Styler.format_null` is now added into the built-in functions to help formatting missing values (:issue:`28358`)
113114

114115
Build Changes
115116
^^^^^^^^^^^^^

pandas/io/formats/style.py

+19
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,25 @@ def hide_columns(self, subset):
930930
# A collection of "builtin" styles
931931
# -----------------------------------------------------------------------
932932

933+
def format_null(self, na_rep="-"):
934+
"""
935+
Format the text displayed for missing values.
936+
937+
.. versionadded:: 1.0.0
938+
939+
Parameters
940+
----------
941+
na_rep : str
942+
943+
Returns
944+
-------
945+
self : Styler
946+
"""
947+
self.format(
948+
lambda x: na_rep if pd.isna(x) else self._display_funcs.default_factory()(x)
949+
)
950+
return self
951+
933952
@staticmethod
934953
def _highlight_null(v, null_color):
935954
return (

pandas/tests/io/formats/test_style.py

+8
Original file line numberDiff line numberDiff line change
@@ -990,6 +990,14 @@ def test_bar_bad_align_raises(self):
990990
with pytest.raises(ValueError):
991991
df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"])
992992

993+
def test_format_null(self, na_rep="-"):
994+
# GH 28358
995+
df = pd.DataFrame({"A": [0, np.nan]})
996+
ctx = df.style.format_null()._translate()
997+
result = ctx["body"][1][1]["display_value"]
998+
expected = "-"
999+
assert result == expected
1000+
9931001
def test_highlight_null(self, null_color="red"):
9941002
df = pd.DataFrame({"A": [0, np.nan]})
9951003
result = df.style.highlight_null()._compute().ctx

0 commit comments

Comments
 (0)