Skip to content

Commit

Permalink
Series.__repr__ with MultiIndex with level name 0
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel committed Oct 5, 2023
1 parent a76b3f4 commit cad0689
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 12 deletions.
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:`??`)
-

.. ***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):
# 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

0 comments on commit cad0689

Please sign in to comment.