diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 84e011bf80da6..c390f57a904cb 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -372,7 +372,7 @@ I/O - Bug in :func:`read_hdf` not properly closing store after a ``IndexError`` is raised (:issue:`52781`) - Bug in :func:`read_html`, style elements were read into DataFrames (:issue:`52197`) - Bug in :func:`read_html`, tail texts were removed together with elements containing ``display:none`` style (:issue:`51629`) -- +- Bug in displaying a :class:`MultiIndex` with a long element (:issue:`52960`) Period ^^^^^^ diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index 0062a4737740e..828f3cf3735e9 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -412,12 +412,14 @@ def best_len(values: list[str]) -> int: # max_space max_space = display_width - len(space2) value = tail[0] - for max_items in reversed(range(1, len(value) + 1)): - pprinted_seq = _pprint_seq(value, max_seq_items=max_items) + max_items = 1 + for num_items in reversed(range(1, len(value) + 1)): + pprinted_seq = _pprint_seq(value, max_seq_items=num_items) if len(pprinted_seq) < max_space: - head = [_pprint_seq(x, max_seq_items=max_items) for x in head] - tail = [_pprint_seq(x, max_seq_items=max_items) for x in tail] + max_items = num_items break + head = [_pprint_seq(x, max_seq_items=max_items) for x in head] + tail = [_pprint_seq(x, max_seq_items=max_items) for x in tail] summary = "" line = space2 diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index 803ed8d342a2f..6f578b45bf71d 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -196,3 +196,14 @@ def test_enable_data_resource_formatter(self, ip): assert formatters[mimetype].enabled # smoke test that it works ip.instance(config=ip.config).display_formatter.format(cf) + + +def test_multiindex_long_element(): + # Non-regression test towards GH #52960 + data = pd.MultiIndex.from_tuples([("c" * 62,)]) + + expected = ( + "MultiIndex([('cccccccccccccccccccccccccccccccccccccccc" + "cccccccccccccccccccccc',)],\n )" + ) + assert str(data) == expected