diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 61848cb127029..5cfa89a39a78f 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -890,6 +890,7 @@ Styler - Bug when attempting to apply styling functions to an empty DataFrame subset (:issue:`45313`) - Bug in :class:`CSSToExcelConverter` leading to ``TypeError`` when border color provided without border style for ``xlsxwriter`` engine (:issue:`42276`) - Bug in :meth:`Styler.set_sticky` leading to white text on white background in dark mode (:issue:`46984`) +- Bug in :meth:`Styler.to_latex` causing ``UnboundLocalError`` when ``clines="all;data"`` and the ``DataFrame`` has no rows. (:issue:`47203`) Metadata ^^^^^^^^ diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 4e3f86d21b228..65720e675a77a 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -908,7 +908,7 @@ def concatenated_visible_rows(obj, n, row_indices): f"of 'all;data', 'all;index', 'skip-last;data', 'skip-last;index'." ) elif clines is not None: - data_len = len(row_body_cells) if "data" in clines else 0 + data_len = len(row_body_cells) if "data" in clines and d["body"] else 0 d["clines"] = defaultdict(list) visible_row_indexes: list[int] = [ diff --git a/pandas/tests/io/formats/style/test_to_latex.py b/pandas/tests/io/formats/style/test_to_latex.py index 4f83b3dafcc0b..b295c955a8967 100644 --- a/pandas/tests/io/formats/style/test_to_latex.py +++ b/pandas/tests/io/formats/style/test_to_latex.py @@ -1032,3 +1032,36 @@ def test_concat_recursion(): """ ) assert result == expected + + +@pytest.mark.parametrize( + "df, expected", + [ + ( + DataFrame(), + dedent( + """\ + \\begin{tabular}{l} + \\end{tabular} + """ + ), + ), + ( + DataFrame(columns=["a", "b", "c"]), + dedent( + """\ + \\begin{tabular}{llll} + & a & b & c \\\\ + \\end{tabular} + """ + ), + ), + ], +) +@pytest.mark.parametrize( + "clines", [None, "all;data", "all;index", "skip-last;data", "skip-last;index"] +) +def test_empty_clines(df: DataFrame, expected: str, clines: str): + # GH 47203 + result = df.style.to_latex(clines=clines) + assert result == expected