Skip to content

Series.__repr__ with MultiIndex with level name 0 #55415

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,8 @@ Styler
Other
^^^^^
- Bug in :func:`cut` incorrectly allowing cutting of timezone-aware datetimes with timezone-naive bins (:issue:`54964`)
- Bug in rendering a :class:`Series` with a :class:`MultiIndex` when one of the index level's names is 0 not having that name displayed (:issue:`55415`)
-

.. ***DO NOT USE THIS SECTION***

Expand Down
14 changes: 2 additions & 12 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,17 +298,6 @@ def _get_footer(self) -> str:

return str(footer)

def _get_formatted_index(self) -> tuple[list[str], bool]:
index = self.tr_series.index

if isinstance(index, MultiIndex):
have_header = any(name for name in index.names)
fmt_index = index.format(names=True)
else:
have_header = index.name is not None
fmt_index = index.format(name=True)
return fmt_index, have_header

def _get_formatted_values(self) -> list[str]:
return format_array(
self.tr_series._values,
Expand All @@ -325,7 +314,8 @@ def to_string(self) -> str:
if len(series) == 0:
return f"{type(self.series).__name__}([], {footer})"

fmt_index, have_header = self._get_formatted_index()
have_header = _has_names(series.index)
fmt_index = self.tr_series.index.format(name=True)
fmt_values = self._get_formatted_values()

if self.is_truncated_vertically:
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/series/test_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@


class TestSeriesRepr:
def test_multilevel_name_print_0(self):
# GH#55415 None does not get printed, but 0 does
# (matching DataFrame and flat index behavior)
mi = pd.MultiIndex.from_product([range(2, 3), range(3, 4)], names=[0, None])
ser = Series(1.5, index=mi)

res = repr(ser)
expected = "0 \n2 3 1.5\ndtype: float64"
assert res == expected

def test_multilevel_name_print(self, lexsorted_two_level_string_multiindex):
index = lexsorted_two_level_string_multiindex
ser = Series(range(len(index)), index=index, name="sth")
Expand Down