diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2f8cb346935a9..b2d73e6d5b2e7 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -423,6 +423,7 @@ Styler - 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`). +- Bug when rendering a single level MultiIndex (:issue:`43383`). Other ^^^^^ diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 49952adf4fb4c..0c6ced17b623e 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -461,7 +461,7 @@ def _translate_body( ) rlabels = self.data.index.tolist()[:max_rows] # slice to allow trimming - if self.data.index.nlevels == 1: + if not isinstance(self.data.index, MultiIndex): rlabels = [[x] for x in rlabels] body = [] @@ -896,7 +896,7 @@ def _get_level_lengths( hidden_elements = [] lengths = {} - if index.nlevels == 1: + if not isinstance(index, MultiIndex): for i, value in enumerate(levels): if i not in hidden_elements: lengths[(0, i)] = 1 diff --git a/pandas/tests/io/formats/style/test_format.py b/pandas/tests/io/formats/style/test_format.py index 532aeb26f6d21..1d0d91b46553a 100644 --- a/pandas/tests/io/formats/style/test_format.py +++ b/pandas/tests/io/formats/style/test_format.py @@ -4,6 +4,7 @@ from pandas import ( DataFrame, IndexSlice, + MultiIndex, NaT, Timestamp, option_context, @@ -305,3 +306,14 @@ def test_precision_zero(df): ctx = styler._translate(True, True) assert ctx["body"][0][2]["display_value"] == "-1" assert ctx["body"][1][2]["display_value"] == "-1" + + +def test_1level_multiindex(): + # GH 43383 + midx = MultiIndex.from_product([[1, 2]], names=[""]) + df = DataFrame(-1, index=midx, columns=[0, 1]) + ctx = df.style._translate(True, True) + assert ctx["body"][0][0]["display_value"] == 1 + assert ctx["body"][0][0]["is_visible"] is True + assert ctx["body"][1][0]["display_value"] == 2 + assert ctx["body"][1][0]["is_visible"] is True