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

Already on GitHub? Sign in to your account

ENH: Print hierarchical index names in Series.__repr__ #334

Closed
wants to merge 2 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+31 −1
Split
View
@@ -405,7 +405,13 @@ def _get_repr(self, name=False, na_rep='NaN'):
vals = self.values
index = self.index
- string_index = index.format()
+ is_multi = isinstance(index, MultiIndex)
+ if is_multi:
+ string_index = index.format(names=True)
+ header, string_index = string_index[0], string_index[1:]
+ else:
+ string_index = index.format()
+
maxlen = max(len(x) for x in string_index)
padSpace = min(maxlen, 60)
@@ -427,6 +433,8 @@ def _format_nonfloat(k, v):
it = itertools.starmap(_format,
itertools.izip(string_index, vals))
it = list(it)
+ if is_multi and any(name for name in index.names):
+ it.insert(0, header)
if name:
namestr = ("Name: %s, " % self.name) if self.name else ""
it.append('%sLength: %d' % (namestr, len(self)))
@@ -64,6 +64,28 @@ def test_getitem_preserve_name(self):
result = self.ts[5:10]
self.assertEquals(result.name, self.ts.name)
+ def test_multilevel_name_print(self):
+ index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
+ ['one', 'two', 'three']],
+ labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
+ [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
+ names=['first', 'second'])
+ s = Series(range(0,len(index)), index=index, name='sth')
+ expected = ["first second",
+ "foo one 0",
+ " two 1",
+ " three 2",
+ "bar one 3",
+ " two 4",
+ "baz two 5",
+ " three 6",
+ "qux one 7",
+ " two 8",
+ " three 9",
+ "Name: sth, Length: 10"]
+ expected = "\n".join(expected)
+ self.assertEquals(s.__repr__(), expected)
+
def test_multilevel_preserve_name(self):
index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
['one', 'two', 'three']],