Skip to content

Commit 5e25572

Browse files
adamkleinwesm
authored andcommitted
ENH: Print hierarchical index names in Series.__repr__
1 parent cbf735a commit 5e25572

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

pandas/core/series.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,13 @@ def _get_repr(self, name=False, na_rep='NaN'):
371371
vals = self.values
372372
index = self.index
373373

374-
string_index = index.format()
374+
is_multi = isinstance(index, MultiIndex)
375+
if is_multi:
376+
string_index = index.format(names=True)
377+
header, string_index = string_index[0], string_index[1:]
378+
else:
379+
string_index = index.format()
380+
375381
maxlen = max(len(x) for x in string_index)
376382
padSpace = min(maxlen, 60)
377383

@@ -393,6 +399,8 @@ def _format_nonfloat(k, v):
393399
it = itertools.starmap(_format,
394400
itertools.izip(string_index, vals))
395401
it = list(it)
402+
if is_multi:
403+
it.insert(0, header)
396404
if name:
397405
namestr = ("Name: %s, " % self.name) if self.name else ""
398406
it.append('%sLength: %d' % (namestr, len(self)))

pandas/tests/test_series.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,28 @@ def test_getitem_preserve_name(self):
6464
result = self.ts[5:10]
6565
self.assertEquals(result.name, self.ts.name)
6666

67+
def test_multilevel_name_print(self):
68+
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
69+
['one', 'two', 'three']],
70+
labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
71+
[0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
72+
names=['first', 'second'])
73+
s = Series(range(0,len(index)), index=index, name='sth')
74+
expected = ["first second",
75+
"foo one 0",
76+
" two 1",
77+
" three 2",
78+
"bar one 3",
79+
" two 4",
80+
"baz two 5",
81+
" three 6",
82+
"qux one 7",
83+
" two 8",
84+
" three 9",
85+
"Name: sth, Length: 10"]
86+
expected = "\n".join(expected)
87+
self.assertEquals(s.__repr__(), expected)
88+
6789
def test_multilevel_preserve_name(self):
6890
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
6991
['one', 'two', 'three']],

0 commit comments

Comments
 (0)