Skip to content

Commit 284cfb2

Browse files
authored
BUG: MultiIndex displays incorrectly with a long element (#53044)
* if branch may not be visited, so head and tail may not be correctly set * fixed pylint possibly undefined variable * updated changelog * added unit test
1 parent 5fa7f31 commit 284cfb2

File tree

3 files changed

+18
-5
lines changed

3 files changed

+18
-5
lines changed

doc/source/whatsnew/v2.1.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ I/O
376376
- Bug in :func:`read_hdf` not properly closing store after a ``IndexError`` is raised (:issue:`52781`)
377377
- Bug in :func:`read_html`, style elements were read into DataFrames (:issue:`52197`)
378378
- Bug in :func:`read_html`, tail texts were removed together with elements containing ``display:none`` style (:issue:`51629`)
379-
-
379+
- Bug in displaying a :class:`MultiIndex` with a long element (:issue:`52960`)
380380

381381
Period
382382
^^^^^^

pandas/io/formats/printing.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -412,12 +412,14 @@ def best_len(values: list[str]) -> int:
412412
# max_space
413413
max_space = display_width - len(space2)
414414
value = tail[0]
415-
for max_items in reversed(range(1, len(value) + 1)):
416-
pprinted_seq = _pprint_seq(value, max_seq_items=max_items)
415+
max_items = 1
416+
for num_items in reversed(range(1, len(value) + 1)):
417+
pprinted_seq = _pprint_seq(value, max_seq_items=num_items)
417418
if len(pprinted_seq) < max_space:
418-
head = [_pprint_seq(x, max_seq_items=max_items) for x in head]
419-
tail = [_pprint_seq(x, max_seq_items=max_items) for x in tail]
419+
max_items = num_items
420420
break
421+
head = [_pprint_seq(x, max_seq_items=max_items) for x in head]
422+
tail = [_pprint_seq(x, max_seq_items=max_items) for x in tail]
421423

422424
summary = ""
423425
line = space2

pandas/tests/io/formats/test_printing.py

+11
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,14 @@ def test_enable_data_resource_formatter(self, ip):
196196
assert formatters[mimetype].enabled
197197
# smoke test that it works
198198
ip.instance(config=ip.config).display_formatter.format(cf)
199+
200+
201+
def test_multiindex_long_element():
202+
# Non-regression test towards GH #52960
203+
data = pd.MultiIndex.from_tuples([("c" * 62,)])
204+
205+
expected = (
206+
"MultiIndex([('cccccccccccccccccccccccccccccccccccccccc"
207+
"cccccccccccccccccccccc',)],\n )"
208+
)
209+
assert str(data) == expected

0 commit comments

Comments
 (0)