diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index be647e344f270..b28b4a663ba54 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -381,7 +381,7 @@ Styler - Bug in :meth:`.Styler.to_html` where the ``Styler`` object was updated if the ``to_html`` method was called with some args (:issue:`43034`) - Bug in :meth:`.Styler.copy` where ``uuid`` was not previously copied (:issue:`40675`) - Bug in :meth:`Styler.apply` where functions which returned Series objects were not correctly handled in terms of aligning their index labels (:issue:`13657`, :issue:`42014`) -- +- Bug when rendering an empty DataFrame with a named index (:issue:`43305`). Other ^^^^^ diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 4f1e98225aafe..d812fe59f05a2 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -393,7 +393,9 @@ def _translate_header( for c, name in enumerate(self.data.index.names) ] - if len(self.data.columns) <= max_cols: + if not clabels: + blank_len = 0 + elif len(self.data.columns) <= max_cols: blank_len = len(clabels[0]) else: blank_len = len(clabels[0]) + 1 # to allow room for `...` trim col diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 5022a1eaa2c6e..352f00292ce24 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -1,5 +1,6 @@ import copy import re +from textwrap import dedent import numpy as np import pytest @@ -187,6 +188,23 @@ def test_render_trimming_mi(): assert {"attributes": 'colspan="2"'}.items() <= ctx["head"][0][2].items() +def test_render_empty_mi(): + # GH 43305 + df = DataFrame(index=MultiIndex.from_product([["A"], [0, 1]], names=[None, "one"])) + expected = dedent( + """\ + > + + +   + one + + + """ + ) + assert expected in df.style.to_html() + + @pytest.mark.parametrize("comprehensive", [True, False]) @pytest.mark.parametrize("render", [True, False]) @pytest.mark.parametrize("deepcopy", [True, False])