diff --git a/asv_bench/benchmarks/io/style.py b/asv_bench/benchmarks/io/style.py
index 82166a2a95c76..a0067307c3905 100644
--- a/asv_bench/benchmarks/io/style.py
+++ b/asv_bench/benchmarks/io/style.py
@@ -36,11 +36,11 @@ def peakmem_classes_render(self, cols, rows):
def time_format_render(self, cols, rows):
self._style_format()
- self.st.render()
+ self.st._render_html(True, True)
def peakmem_format_render(self, cols, rows):
self._style_format()
- self.st.render()
+ self.st._render_html(True, True)
def _style_apply(self):
def _apply_func(s):
diff --git a/doc/source/reference/style.rst b/doc/source/reference/style.rst
index ac4fc314c6c07..11d57e66c4773 100644
--- a/doc/source/reference/style.rst
+++ b/doc/source/reference/style.rst
@@ -71,9 +71,8 @@ Style export and import
.. autosummary::
:toctree: api/
- Styler.render
- Styler.export
- Styler.use
Styler.to_html
- Styler.to_excel
Styler.to_latex
+ Styler.to_excel
+ Styler.export
+ Styler.use
diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb
index 10ef65a68eefa..4de54c5d9471c 100644
--- a/doc/source/user_guide/style.ipynb
+++ b/doc/source/user_guide/style.ipynb
@@ -60,9 +60,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The above output looks very similar to the standard DataFrame HTML representation. But the HTML here has already attached some CSS classes to each cell, even if we haven't yet created any styles. We can view these by calling the [.render()][render] method, which returns the raw HTML as string, which is useful for further processing or adding to a file - read on in [More about CSS and HTML](#More-About-CSS-and-HTML). Below we will show how we can use these to format the DataFrame to be more communicative. For example how we can build `s`:\n",
+ "The above output looks very similar to the standard DataFrame HTML representation. But the HTML here has already attached some CSS classes to each cell, even if we haven't yet created any styles. We can view these by calling the [.to_html()][to_html] method, which returns the raw HTML as string, which is useful for further processing or adding to a file - read on in [More about CSS and HTML](#More-About-CSS-and-HTML). Below we will show how we can use these to format the DataFrame to be more communicative. For example how we can build `s`:\n",
"\n",
- "[render]: ../reference/api/pandas.io.formats.style.Styler.render.rst"
+ "[tohtml]: ../reference/api/pandas.io.formats.style.Styler.to_html.rst"
]
},
{
@@ -381,7 +381,7 @@
"metadata": {},
"outputs": [],
"source": [
- "out = s.set_table_attributes('class=\"my-table-cls\"').render()\n",
+ "out = s.set_table_attributes('class=\"my-table-cls\"').to_html()\n",
"print(out[out.find('
{}\".format(s.to_frame().style.hide_index().bar(align=align, \n",
" color=['#d65f5f', '#5fba7d'], \n",
- " width=100).render()) #testn['width']\n",
+ " width=100).to_html()) #testn['width']\n",
" row += ''\n",
" head += row\n",
" \n",
@@ -1616,9 +1616,9 @@
"\n",
"The structure of the `id` is `T_uuid_level_row_col` where `level` is used only on headings, and headings will only have either `row` or `col` whichever is needed. By default we've also prepended each row/column identifier with a UUID unique to each DataFrame so that the style from one doesn't collide with the styling from another within the same notebook or page. You can read more about the use of UUIDs in [Optimization](#Optimization).\n",
"\n",
- "We can see example of the HTML by calling the [.render()][render] method.\n",
+ "We can see example of the HTML by calling the [.to_html()][tohtml] method.\n",
"\n",
- "[render]: ../reference/api/pandas.io.formats.style.Styler.render.rst"
+ "[tohtml]: ../reference/api/pandas.io.formats.style.Styler.to_html.rst"
]
},
{
@@ -1627,7 +1627,7 @@
"metadata": {},
"outputs": [],
"source": [
- "print(pd.DataFrame([[1,2],[3,4]], index=['i1', 'i2'], columns=['c1', 'c2']).style.render())"
+ "print(pd.DataFrame([[1,2],[3,4]], index=['i1', 'i2'], columns=['c1', 'c2']).style.to_html())"
]
},
{
@@ -1854,7 +1854,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Our custom template accepts a `table_title` keyword. We can provide the value in the `.render` method."
+ "Our custom template accepts a `table_title` keyword. We can provide the value in the `.to_html` method."
]
},
{
@@ -1863,7 +1863,7 @@
"metadata": {},
"outputs": [],
"source": [
- "HTML(MyStyler(df3).render(table_title=\"Extending Example\"))"
+ "HTML(MyStyler(df3).to_html(table_title=\"Extending Example\"))"
]
},
{
@@ -1880,7 +1880,7 @@
"outputs": [],
"source": [
"EasyStyler = Styler.from_custom_template(\"templates\", \"myhtml.tpl\")\n",
- "HTML(EasyStyler(df3).render(table_title=\"Another Title\"))"
+ "HTML(EasyStyler(df3).to_html(table_title=\"Another Title\"))"
]
},
{
@@ -1990,7 +1990,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.8.6"
+ "version": "3.8.7"
}
},
"nbformat": 4,
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index f0af60f80edd5..b5e1dc51a5a2d 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -208,7 +208,7 @@ Deprecations
- Deprecated the 'kind' argument in :meth:`Index.get_slice_bound`, :meth:`Index.slice_indexer`, :meth:`Index.slice_locs`; in a future version passing 'kind' will raise (:issue:`42857`)
- Deprecated dropping of nuisance columns in :class:`Rolling`, :class:`Expanding`, and :class:`EWM` aggregations (:issue:`42738`)
- Deprecated :meth:`Index.reindex` with a non-unique index (:issue:`42568`)
--
+- Deprecated :meth:`.Styler.render` in favour of :meth:`.Styler.to_html` (:issue:`42140`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index a72de753d6a8a..cc64dffc121e5 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -151,7 +151,7 @@ class Styler(StylerRenderer):
be applied to the indicated cells.
If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
- to automatically render itself. Otherwise call Styler.render to get
+ to automatically render itself. Otherwise call Styler.to_html to get
the generated HTML.
CSS classes are attached to the generated HTML
@@ -214,7 +214,7 @@ def _repr_html_(self) -> str:
"""
Hooks into Jupyter notebook rich display system.
"""
- return self.render()
+ return self.to_html()
def render(
self,
@@ -225,6 +225,8 @@ def render(
"""
Render the ``Styler`` including all applied styles to HTML.
+ .. deprecated:: 1.4.0
+
Parameters
----------
sparse_index : bool, optional
@@ -248,11 +250,14 @@ def render(
Notes
-----
+ This method is deprecated in favour of ``Styler.to_html``.
+
Styler objects have defined the ``_repr_html_`` method
- which automatically calls ``self.render()`` when it's the
- last item in a Notebook cell. When calling ``Styler.render()``
- directly, wrap the result in ``IPython.display.HTML`` to view
- the rendered HTML in the notebook.
+ which automatically calls ``self.to_html()`` when it's the
+ last item in a Notebook cell.
+
+ When calling ``Styler.render()`` directly, wrap the result in
+ ``IPython.display.HTML`` to view the rendered HTML in the notebook.
Pandas uses the following keys in render. Arguments passed
in ``**kwargs`` take precedence, so think carefully if you want
@@ -266,6 +271,11 @@ def render(
* caption
* table_attributes
"""
+ warnings.warn(
+ "this method is deprecated in favour of `Styler.to_html()`",
+ FutureWarning,
+ stacklevel=2,
+ )
if sparse_index is None:
sparse_index = get_option("styler.sparse.index")
if sparse_columns is None:
@@ -336,7 +346,7 @@ def set_tooltips(
>>> ttips = pd.DataFrame(
... data=[["Min", ""], [np.nan, "Max"]], columns=df.columns, index=df.index
... )
- >>> s = df.style.set_tooltips(ttips).render()
+ >>> s = df.style.set_tooltips(ttips).to_html()
Optionally controlling the tooltip visual display
@@ -550,7 +560,7 @@ def to_latex(
>>> df = pd.DataFrame([[1,2], [3,4]])
>>> s = df.style.highlight_max(axis=None,
... props='background-color:red; font-weight:bold;')
- >>> s.render() # doctest: +SKIP
+ >>> s.to_html() # doctest: +SKIP
The equivalent using LaTeX only commands is the following:
@@ -831,6 +841,7 @@ def to_html(
encoding: str | None = None,
doctype_html: bool = False,
exclude_styles: bool = False,
+ **kwargs,
):
"""
Write Styler to a file, buffer or string in HTML-CSS format.
@@ -875,6 +886,10 @@ def to_html(
Whether to include the ``'
''
' '
diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py
index aa58b3abbd06c..979af71444854 100644
--- a/pandas/io/formats/style_render.py
+++ b/pandas/io/formats/style_render.py
@@ -735,7 +735,7 @@ def format(
>>> s = df.style.format(
... '{0}', escape="html", na_rep="NA"
... )
- >>> s.render() # doctest: +SKIP
+ >>> s.to_html() # doctest: +SKIP
...
<div></div> |
"A&B" |
diff --git a/pandas/tests/io/formats/style/test_deprecated.py b/pandas/tests/io/formats/style/test_deprecated.py
new file mode 100644
index 0000000000000..a582761d7bff7
--- /dev/null
+++ b/pandas/tests/io/formats/style/test_deprecated.py
@@ -0,0 +1,159 @@
+"""
+modules collects tests for Styler methods which have been deprecated
+"""
+import numpy as np
+import pytest
+
+jinja2 = pytest.importorskip("jinja2")
+
+from pandas import (
+ DataFrame,
+ IndexSlice,
+ NaT,
+ Timestamp,
+)
+import pandas._testing as tm
+
+
+@pytest.fixture
+def df():
+ return DataFrame({"A": [0, 1], "B": np.random.randn(2)})
+
+
+def test_set_non_numeric_na():
+ # GH 21527 28358
+ df = DataFrame(
+ {
+ "object": [None, np.nan, "foo"],
+ "datetime": [None, NaT, Timestamp("20120101")],
+ }
+ )
+
+ with tm.assert_produces_warning(FutureWarning):
+ ctx = df.style.set_na_rep("NA")._translate(True, True)
+ assert ctx["body"][0][1]["display_value"] == "NA"
+ assert ctx["body"][0][2]["display_value"] == "NA"
+ assert ctx["body"][1][1]["display_value"] == "NA"
+ assert ctx["body"][1][2]["display_value"] == "NA"
+
+
+def test_where_with_one_style(df):
+ # GH 17474
+ def f(x):
+ return x > 0.5
+
+ style1 = "foo: bar"
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = df.style.where(f, style1)._compute().ctx
+ expected = {
+ (r, c): [("foo", "bar")]
+ for r, row in enumerate(df.index)
+ for c, col in enumerate(df.columns)
+ if f(df.loc[row, col])
+ }
+ assert result == expected
+
+
+@pytest.mark.parametrize(
+ "slice_",
+ [
+ IndexSlice[:],
+ IndexSlice[:, ["A"]],
+ IndexSlice[[1], :],
+ IndexSlice[[1], ["A"]],
+ IndexSlice[:2, ["A", "B"]],
+ ],
+)
+def test_where_subset(df, slice_):
+ # GH 17474
+ def f(x):
+ return x > 0.5
+
+ style1 = "foo: bar"
+ style2 = "baz: foo"
+
+ with tm.assert_produces_warning(FutureWarning):
+ res = df.style.where(f, style1, style2, subset=slice_)._compute().ctx
+ expected = {
+ (r, c): [("foo", "bar") if f(df.loc[row, col]) else ("baz", "foo")]
+ for r, row in enumerate(df.index)
+ for c, col in enumerate(df.columns)
+ if row in df.loc[slice_].index and col in df.loc[slice_].columns
+ }
+ assert res == expected
+
+
+def test_where_subset_compare_with_applymap(df):
+ # GH 17474
+ def f(x):
+ return x > 0.5
+
+ style1 = "foo: bar"
+ style2 = "baz: foo"
+
+ def g(x):
+ return style1 if f(x) else style2
+
+ slices = [
+ IndexSlice[:],
+ IndexSlice[:, ["A"]],
+ IndexSlice[[1], :],
+ IndexSlice[[1], ["A"]],
+ IndexSlice[:2, ["A", "B"]],
+ ]
+
+ for slice_ in slices:
+ with tm.assert_produces_warning(FutureWarning):
+ result = df.style.where(f, style1, style2, subset=slice_)._compute().ctx
+ expected = df.style.applymap(g, subset=slice_)._compute().ctx
+ assert result == expected
+
+
+def test_where_kwargs():
+ df = DataFrame([[1, 2], [3, 4]])
+
+ def f(x, val):
+ return x > val
+
+ with tm.assert_produces_warning(FutureWarning):
+ res = df.style.where(f, "color:green;", "color:red;", val=2)._compute().ctx
+ expected = {
+ (0, 0): [("color", "red")],
+ (0, 1): [("color", "red")],
+ (1, 0): [("color", "green")],
+ (1, 1): [("color", "green")],
+ }
+ assert res == expected
+
+
+def test_set_na_rep():
+ # GH 21527 28358
+ df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
+
+ with tm.assert_produces_warning(FutureWarning):
+ ctx = df.style.set_na_rep("NA")._translate(True, True)
+ assert ctx["body"][0][1]["display_value"] == "NA"
+ assert ctx["body"][0][2]["display_value"] == "NA"
+
+ with tm.assert_produces_warning(FutureWarning):
+ ctx = (
+ df.style.set_na_rep("NA")
+ .format(None, na_rep="-", subset=["B"])
+ ._translate(True, True)
+ )
+ assert ctx["body"][0][1]["display_value"] == "NA"
+ assert ctx["body"][0][2]["display_value"] == "-"
+
+
+def test_precision(df):
+ styler = df.style
+ with tm.assert_produces_warning(FutureWarning):
+ s2 = styler.set_precision(1)
+ assert styler is s2
+ assert styler.precision == 1
+
+
+def test_render(df):
+ with tm.assert_produces_warning(FutureWarning):
+ df.style.render()
diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py
index 77a547098036c..299643028c141 100644
--- a/pandas/tests/io/formats/style/test_format.py
+++ b/pandas/tests/io/formats/style/test_format.py
@@ -7,7 +7,6 @@
NaT,
Timestamp,
)
-import pandas._testing as tm
pytest.importorskip("jinja2")
from pandas.io.formats.style import Styler
@@ -84,14 +83,6 @@ def test_format_non_numeric_na():
"datetime": [None, NaT, Timestamp("20120101")],
}
)
-
- with tm.assert_produces_warning(FutureWarning):
- ctx = df.style.set_na_rep("NA")._translate(True, True)
- assert ctx["body"][0][1]["display_value"] == "NA"
- assert ctx["body"][0][2]["display_value"] == "NA"
- assert ctx["body"][1][1]["display_value"] == "NA"
- assert ctx["body"][1][2]["display_value"] == "NA"
-
ctx = df.style.format(None, na_rep="-")._translate(True, True)
assert ctx["body"][0][1]["display_value"] == "-"
assert ctx["body"][0][2]["display_value"] == "-"
@@ -125,12 +116,12 @@ def test_format_escape_html(escape, exp):
s = Styler(df, uuid_len=0).format("&{0}&", escape=None)
expected = f'&{chars}& | '
- assert expected in s.render()
+ assert expected in s.to_html()
# only the value should be escaped before passing to the formatter
s = Styler(df, uuid_len=0).format("&{0}&", escape=escape)
expected = f'&{exp}& | '
- assert expected in s.render()
+ assert expected in s.to_html()
def test_format_escape_na_rep():
@@ -139,19 +130,19 @@ def test_format_escape_na_rep():
s = Styler(df, uuid_len=0).format("X&{0}>X", escape="html", na_rep="&")
ex = 'X&<>&">X | '
expected2 = '& | '
- assert ex in s.render()
- assert expected2 in s.render()
+ assert ex in s.to_html()
+ assert expected2 in s.to_html()
def test_format_escape_floats(styler):
# test given formatter for number format is not impacted by escape
s = styler.format("{:.1f}", escape="html")
for expected in [">0.0<", ">1.0<", ">-1.2<", ">-0.6<"]:
- assert expected in s.render()
+ assert expected in s.to_html()
# tests precision of floats is not impacted by escape
s = styler.format(precision=1, escape="html")
for expected in [">0<", ">1<", ">-1.2<", ">-0.6<"]:
- assert expected in s.render()
+ assert expected in s.to_html()
@pytest.mark.parametrize("formatter", [5, True, [2.0]])
diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py
index bcf3c4dbad3a8..6b8511e4b4c23 100644
--- a/pandas/tests/io/formats/style/test_html.py
+++ b/pandas/tests/io/formats/style/test_html.py
@@ -124,21 +124,21 @@ def test_w3_html_format(styler):
"""
)
- assert expected == styler.render()
+ assert expected == styler.to_html()
def test_colspan_w3():
# GH 36223
df = DataFrame(data=[[1, 2]], columns=[["l0", "l0"], ["l1a", "l1b"]])
styler = Styler(df, uuid="_", cell_ids=False)
- assert 'l0 | ' in styler.render()
+ assert 'l0 | ' in styler.to_html()
def test_rowspan_w3():
# GH 38533
df = DataFrame(data=[[1, 2]], index=[["l0", "l0"], ["l1a", "l1b"]])
styler = Styler(df, uuid="_", cell_ids=False)
- assert 'l0 | ' in styler.render()
+ assert 'l0 | ' in styler.to_html()
def test_styles(styler):
@@ -238,7 +238,7 @@ def test_from_custom_template_table(tmpdir):
assert result.env is not Styler.env
assert result.template_html_table is not Styler.template_html_table
styler = result(DataFrame({"A": [1, 2]}))
- assert "My Title
\n\n\nMy Title\n\n\nfull cap" in styler.render()
+ assert "full cap" in styler.to_html()
@pytest.mark.parametrize("index", [False, True])
diff --git a/pandas/tests/io/formats/style/test_non_unique.py b/pandas/tests/io/formats/style/test_non_unique.py
index fc04169091c09..5bb593f20e9d5 100644
--- a/pandas/tests/io/formats/style/test_non_unique.py
+++ b/pandas/tests/io/formats/style/test_non_unique.py
@@ -31,14 +31,14 @@ def test_format_non_unique(df):
# GH 41269
# test dict
- html = df.style.format({"d": "{:.1f}"}).render()
+ html = df.style.format({"d": "{:.1f}"}).to_html()
for val in ["1.000000<", "4.000000<", "7.000000<"]:
assert val in html
for val in ["2.0<", "3.0<", "5.0<", "6.0<", "8.0<", "9.0<"]:
assert val in html
# test subset
- html = df.style.format(precision=1, subset=IndexSlice["j", "d"]).render()
+ html = df.style.format(precision=1, subset=IndexSlice["j", "d"]).to_html()
for val in ["1.000000<", "4.000000<", "7.000000<", "2.000000<", "3.000000<"]:
assert val in html
for val in ["5.0<", "6.0<", "8.0<", "9.0<"]:
diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py
index 6cc4b889d369a..e0b0aade55477 100644
--- a/pandas/tests/io/formats/style/test_style.py
+++ b/pandas/tests/io/formats/style/test_style.py
@@ -133,16 +133,16 @@ def test_mi_styler_sparsify_index(mi_styler, sparse_index, exp_rows):
def test_mi_styler_sparsify_options(mi_styler):
with pd.option_context("styler.sparse.index", False):
- html1 = mi_styler.render()
+ html1 = mi_styler.to_html()
with pd.option_context("styler.sparse.index", True):
- html2 = mi_styler.render()
+ html2 = mi_styler.to_html()
assert html1 != html2
with pd.option_context("styler.sparse.columns", False):
- html1 = mi_styler.render()
+ html1 = mi_styler.to_html()
with pd.option_context("styler.sparse.columns", True):
- html2 = mi_styler.render()
+ html2 = mi_styler.to_html()
assert html1 != html2
@@ -408,26 +408,26 @@ def test_render(self):
df = DataFrame({"A": [0, 1]})
style = lambda x: pd.Series(["color: red", "color: blue"], name=x.name)
s = Styler(df, uuid="AB").apply(style)
- s.render()
+ s.to_html()
# it worked?
def test_multiple_render(self):
# GH 39396
s = Styler(self.df, uuid_len=0).applymap(lambda x: "color: red;", subset=["A"])
- s.render() # do 2 renders to ensure css styles not duplicated
+ s.to_html() # do 2 renders to ensure css styles not duplicated
assert (
'" in s.render()
+ " color: red;\n}\n" in s.to_html()
)
def test_render_empty_dfs(self):
empty_df = DataFrame()
es = Styler(empty_df)
- es.render()
+ es.to_html()
# An index but no columns
- DataFrame(columns=["a"]).style.render()
+ DataFrame(columns=["a"]).style.to_html()
# A column but no index
- DataFrame(index=["a"]).style.render()
+ DataFrame(index=["a"]).style.to_html()
# No IndexError raised?
def test_render_double(self):
@@ -436,7 +436,7 @@ def test_render_double(self):
["color: red; border: 1px", "color: blue; border: 2px"], name=x.name
)
s = Styler(df, uuid="AB").apply(style)
- s.render()
+ s.to_html()
# it worked?
def test_set_properties(self):
@@ -633,7 +633,7 @@ def test_applymap_subset_multiindex(self, slice_):
df = DataFrame(np.random.rand(4, 4), columns=col, index=idx)
with tm.assert_produces_warning(warn, match=msg, check_stacklevel=False):
- df.style.applymap(lambda x: "color: red;", subset=slice_).render()
+ df.style.applymap(lambda x: "color: red;", subset=slice_).to_html()
def test_applymap_subset_multiindex_code(self):
# https://github.com/pandas-dev/pandas/issues/25858
@@ -654,94 +654,6 @@ def color_negative_red(val):
df.loc[pct_subset]
df.style.applymap(color_negative_red, subset=pct_subset)
- def test_where_with_one_style(self):
- # GH 17474
- def f(x):
- return x > 0.5
-
- style1 = "foo: bar"
-
- with tm.assert_produces_warning(FutureWarning):
- result = self.df.style.where(f, style1)._compute().ctx
- expected = {
- (r, c): [("foo", "bar")]
- for r, row in enumerate(self.df.index)
- for c, col in enumerate(self.df.columns)
- if f(self.df.loc[row, col])
- }
- assert result == expected
-
- @pytest.mark.parametrize(
- "slice_",
- [
- pd.IndexSlice[:],
- pd.IndexSlice[:, ["A"]],
- pd.IndexSlice[[1], :],
- pd.IndexSlice[[1], ["A"]],
- pd.IndexSlice[:2, ["A", "B"]],
- ],
- )
- def test_where_subset(self, slice_):
- # GH 17474
- def f(x):
- return x > 0.5
-
- style1 = "foo: bar"
- style2 = "baz: foo"
-
- with tm.assert_produces_warning(FutureWarning):
- res = self.df.style.where(f, style1, style2, subset=slice_)._compute().ctx
- expected = {
- (r, c): [("foo", "bar") if f(self.df.loc[row, col]) else ("baz", "foo")]
- for r, row in enumerate(self.df.index)
- for c, col in enumerate(self.df.columns)
- if row in self.df.loc[slice_].index and col in self.df.loc[slice_].columns
- }
- assert res == expected
-
- def test_where_subset_compare_with_applymap(self):
- # GH 17474
- def f(x):
- return x > 0.5
-
- style1 = "foo: bar"
- style2 = "baz: foo"
-
- def g(x):
- return style1 if f(x) else style2
-
- slices = [
- pd.IndexSlice[:],
- pd.IndexSlice[:, ["A"]],
- pd.IndexSlice[[1], :],
- pd.IndexSlice[[1], ["A"]],
- pd.IndexSlice[:2, ["A", "B"]],
- ]
-
- for slice_ in slices:
- with tm.assert_produces_warning(FutureWarning):
- result = (
- self.df.style.where(f, style1, style2, subset=slice_)._compute().ctx
- )
- expected = self.df.style.applymap(g, subset=slice_)._compute().ctx
- assert result == expected
-
- def test_where_kwargs(self):
- df = DataFrame([[1, 2], [3, 4]])
-
- def f(x, val):
- return x > val
-
- with tm.assert_produces_warning(FutureWarning):
- res = df.style.where(f, "color:green;", "color:red;", val=2)._compute().ctx
- expected = {
- (0, 0): [("color", "red")],
- (0, 1): [("color", "red")],
- (1, 0): [("color", "green")],
- (1, 1): [("color", "green")],
- }
- assert res == expected
-
def test_empty(self):
df = DataFrame({"A": [1, 0]})
s = df.style
@@ -773,27 +685,9 @@ def test_init_with_na_rep(self):
assert ctx["body"][0][1]["display_value"] == "NA"
assert ctx["body"][0][2]["display_value"] == "NA"
- def test_set_na_rep(self):
- # GH 21527 28358
- df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"])
-
- with tm.assert_produces_warning(FutureWarning):
- ctx = df.style.set_na_rep("NA")._translate(True, True)
- assert ctx["body"][0][1]["display_value"] == "NA"
- assert ctx["body"][0][2]["display_value"] == "NA"
-
- with tm.assert_produces_warning(FutureWarning):
- ctx = (
- df.style.set_na_rep("NA")
- .format(None, na_rep="-", subset=["B"])
- ._translate(True, True)
- )
- assert ctx["body"][0][1]["display_value"] == "NA"
- assert ctx["body"][0][2]["display_value"] == "-"
-
def test_caption(self):
styler = Styler(self.df, caption="foo")
- result = styler.render()
+ result = styler.to_html()
assert all(["caption" in result, "foo" in result])
styler = self.df.style
@@ -803,7 +697,7 @@ def test_caption(self):
def test_uuid(self):
styler = Styler(self.df, uuid="abc123")
- result = styler.render()
+ result = styler.to_html()
assert "abc123" in result
styler = self.df.style
@@ -814,7 +708,7 @@ def test_uuid(self):
def test_unique_id(self):
# See https://github.com/pandas-dev/pandas/issues/16780
df = DataFrame({"a": [1, 3, 5, 6], "b": [2, 4, 12, 21]})
- result = df.style.render(uuid="test")
+ result = df.style.to_html(uuid="test")
assert "test" in result
ids = re.findall('id="(.*?)"', result)
assert np.unique(ids).size == len(ids)
@@ -822,7 +716,7 @@ def test_unique_id(self):
def test_table_styles(self):
style = [{"selector": "th", "props": [("foo", "bar")]}] # default format
styler = Styler(self.df, table_styles=style)
- result = " ".join(styler.render().split())
+ result = " ".join(styler.to_html().split())
assert "th { foo: bar; }" in result
styler = self.df.style
@@ -833,7 +727,7 @@ def test_table_styles(self):
# GH 39563
style = [{"selector": "th", "props": "foo:bar;"}] # css string format
styler = self.df.style.set_table_styles(style)
- result = " ".join(styler.render().split())
+ result = " ".join(styler.to_html().split())
assert "th { foo: bar; }" in result
def test_table_styles_multiple(self):
@@ -864,21 +758,12 @@ def test_maybe_convert_css_to_tuples_err(self):
def test_table_attributes(self):
attributes = 'class="foo" data-bar'
styler = Styler(self.df, table_attributes=attributes)
- result = styler.render()
+ result = styler.to_html()
assert 'class="foo" data-bar' in result
- result = self.df.style.set_table_attributes(attributes).render()
+ result = self.df.style.set_table_attributes(attributes).to_html()
assert 'class="foo" data-bar' in result
- def test_precision(self):
- s = Styler(self.df, precision=2)
- assert s.precision == 2
-
- with tm.assert_produces_warning(FutureWarning):
- s2 = s.set_precision(4)
- assert s is s2
- assert s.precision == 4
-
def test_apply_none(self):
def f(x):
return DataFrame(
@@ -891,10 +776,10 @@ def f(x):
assert result[(1, 1)] == [("color", "red")]
def test_trim(self):
- result = self.df.style.render() # trim=True
+ result = self.df.style.to_html() # trim=True
assert result.count("#") == 0
- result = self.df.style.highlight_max().render()
+ result = self.df.style.highlight_max().to_html()
assert result.count("#") == len(self.df.columns)
def test_export(self):
@@ -906,7 +791,7 @@ def test_export(self):
style2 = self.df.style
style2.use(result)
assert style1._todo == style2._todo
- style2.render()
+ style2.to_html()
def test_bad_apply_shape(self):
df = DataFrame([[1, 2], [3, 4]])
@@ -1252,7 +1137,7 @@ def set_caption_from_template(styler, a, b):
return styler.set_caption(f"Dataframe with a = {a} and b = {b}")
styler = self.df.style.pipe(set_caption_from_template, "A", b="B")
- assert "Dataframe with a = A and b = B" in styler.render()
+ assert "Dataframe with a = A and b = B" in styler.to_html()
# Test with an argument that is a (callable, keyword_name) pair.
def f(a, b, styler):
@@ -1267,8 +1152,8 @@ def test_no_cell_ids(self):
# GH 35663
df = DataFrame(data=[[0]])
styler = Styler(df, uuid="_", cell_ids=False)
- styler.render()
- s = styler.render() # render twice to ensure ctx is not updated
+ styler.to_html()
+ s = styler.to_html() # render twice to ensure ctx is not updated
assert s.find('') != -1
@pytest.mark.parametrize(
@@ -1286,13 +1171,13 @@ def test_no_cell_ids(self):
def test_set_data_classes(self, classes):
# GH 36159
df = DataFrame(data=[[0, 1], [2, 3]], columns=["A", "B"], index=["a", "b"])
- s = Styler(df, uuid_len=0, cell_ids=False).set_td_classes(classes).render()
+ s = Styler(df, uuid_len=0, cell_ids=False).set_td_classes(classes).to_html()
assert ' | 0 | ' in s
assert '1 | ' in s
assert '2 | ' in s
assert '3 | ' in s
# GH 39317
- s = Styler(df, uuid_len=0, cell_ids=True).set_td_classes(classes).render()
+ s = Styler(df, uuid_len=0, cell_ids=True).set_td_classes(classes).to_html()
assert '0 | ' in s
assert '1 | ' in s
assert '2 | ' in s
@@ -1308,7 +1193,7 @@ def test_set_data_classes_reindex(self):
columns=[0, 2],
index=[0, 2],
)
- s = Styler(df, uuid_len=0).set_td_classes(classes).render()
+ s = Styler(df, uuid_len=0).set_td_classes(classes).to_html()
assert '0 | ' in s
assert '2 | ' in s
assert '4 | ' in s
@@ -1331,17 +1216,17 @@ def test_column_and_row_styling(self):
df = DataFrame(data=[[0, 1], [1, 2]], columns=["A", "B"])
s = Styler(df, uuid_len=0)
s = s.set_table_styles({"A": [{"selector": "", "props": [("color", "blue")]}]})
- assert "#T__ .col0 {\n color: blue;\n}" in s.render()
+ assert "#T__ .col0 {\n color: blue;\n}" in s.to_html()
s = s.set_table_styles(
{0: [{"selector": "", "props": [("color", "blue")]}]}, axis=1
)
- assert "#T__ .row0 {\n color: blue;\n}" in s.render()
+ assert "#T__ .row0 {\n color: blue;\n}" in s.to_html()
@pytest.mark.parametrize("len_", [1, 5, 32, 33, 100])
def test_uuid_len(self, len_):
# GH 36345
df = DataFrame(data=[["A"]])
- s = Styler(df, uuid_len=len_, cell_ids=False).render()
+ s = Styler(df, uuid_len=len_, cell_ids=False).to_html()
strt = s.find('id="T_')
end = s[strt + 6 :].find('"')
if len_ > 32:
@@ -1355,7 +1240,7 @@ def test_uuid_len_raises(self, len_):
df = DataFrame(data=[["A"]])
msg = "``uuid_len`` must be an integer in range \\[0, 32\\]."
with pytest.raises(TypeError, match=msg):
- Styler(df, uuid_len=len_, cell_ids=False).render()
+ Styler(df, uuid_len=len_, cell_ids=False).to_html()
@pytest.mark.parametrize(
"slc",
diff --git a/pandas/tests/io/formats/style/test_tooltip.py b/pandas/tests/io/formats/style/test_tooltip.py
index 71ce496cca030..1bef89be78377 100644
--- a/pandas/tests/io/formats/style/test_tooltip.py
+++ b/pandas/tests/io/formats/style/test_tooltip.py
@@ -36,7 +36,7 @@ def styler(df):
)
def test_tooltip_render(ttips, styler):
# GH 21266
- result = styler.set_tooltips(ttips).render()
+ result = styler.set_tooltips(ttips).to_html()
# test tooltip table level class
assert "#T__ .pd-t {\n visibility: hidden;\n" in result
@@ -61,7 +61,7 @@ def test_tooltip_render(ttips, styler):
def test_tooltip_ignored(styler):
# GH 21266
- result = styler.render() # no set_tooltips() creates no
+ result = styler.to_html() # no set_tooltips() creates no
assert '' in result
assert '' not in result
@@ -72,7 +72,7 @@ def test_tooltip_css_class(styler):
DataFrame([["tooltip"]], index=["x"], columns=["A"]),
css_class="other-class",
props=[("color", "green")],
- ).render()
+ ).to_html()
assert "#T__ .other-class {\n color: green;\n" in result
assert '#T__ #T__row0_col0 .other-class::after {\n content: "tooltip";\n' in result
@@ -81,5 +81,5 @@ def test_tooltip_css_class(styler):
DataFrame([["tooltip"]], index=["x"], columns=["A"]),
css_class="another-class",
props="color:green;color:red;",
- ).render()
+ ).to_html()
assert "#T__ .another-class {\n color: green;\n color: red;\n}" in result