Skip to content

Commit

Permalink
Merge pull request #4935 from jtratner/multiindex-smart-repr
Browse files Browse the repository at this point in the history
ENH: Better string representation for MultiIndex
  • Loading branch information
jtratner committed Sep 27, 2013
2 parents ed81ed0 + 8fe542b commit 6260e29
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
2 changes: 2 additions & 0 deletions doc/source/release.rst
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ Improvements to existing features
(:issue:`3441`, :issue:`4933`)
- ``pandas`` is now tested with two different versions of ``statsmodels``
(0.4.3 and 0.5.0) (:issue:`4981`).
- Better string representations of ``MultiIndex`` (including ability to roundtrip
via ``repr``). (:issue:`3347`, :issue:`4935`)

API Changes
~~~~~~~~~~~
Expand Down
40 changes: 33 additions & 7 deletions pandas/core/index.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# pylint: disable=E1101,E1103,W0232
from functools import partial
from pandas.compat import range, zip, lrange, lzip
from pandas.compat import range, zip, lrange, lzip, u
from pandas import compat
import numpy as np

Expand All @@ -17,6 +17,10 @@
from pandas.core.common import _values_from_object, is_float, is_integer
from pandas.core.config import get_option

# simplify
default_pprint = lambda x: com.pprint_thing(x, escape_chars=('\t', '\r', '\n'),
quote_strings=True)


__all__ = ['Index']

Expand Down Expand Up @@ -2052,18 +2056,40 @@ def _array_values(self):
def dtype(self):
return np.dtype('O')

def __repr__(self):
encoding = get_option('display.encoding')
attrs = [('levels', default_pprint(self.levels)),
('labels', default_pprint(self.labels))]
if not all(name is None for name in self.names):
attrs.append(('names', default_pprint(self.names)))
if self.sortorder is not None:
attrs.append(('sortorder', default_pprint(self.sortorder)))

space = ' ' * (len(self.__class__.__name__) + 1)
prepr = (u("\n%s") % space).join([u("%s=%s") % (k, v)
for k, v in attrs])
res = u("%s(%s)") % (self.__class__.__name__, prepr)

if not compat.PY3:
# needs to be str in Python 2
res = res.encode(encoding)
return res


def __unicode__(self):
"""
Return a string representation for a particular Index
Invoked by unicode(df) in py2 only. Yields a Unicode String in both py2/py3.
"""
output = 'MultiIndex\n%s'

summary = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'),
quote_strings=True)

return output % summary
rows = self.format(names=True)
max_rows = get_option('display.max_rows')
if len(rows) > max_rows:
spaces = (len(rows[0]) - 3) // 2
centered = ' ' * spaces
half = max_rows // 2
rows = rows[:half] + [centered + '...' + centered] + rows[-half:]
return "\n".join(rows)

def __len__(self):
return len(self.labels[0])
Expand Down

0 comments on commit 6260e29

Please sign in to comment.