diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 19bda851e392b..9a4e65819422b 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -543,3 +543,5 @@ Bug Fixes - Bug in ``Series.values_counts`` with excluding ``NaN`` for categorical type ``Series`` with ``dropna=True`` (:issue:`9443`) + +- Bug in ``DataFrameFormatter._get_formatted_index`` with not applying ``max_colwidth`` to the ``DataFrame`` index (:issue:`7856`) diff --git a/pandas/core/format.py b/pandas/core/format.py index 3efcfec254591..0d154a587acaf 100644 --- a/pandas/core/format.py +++ b/pandas/core/format.py @@ -746,6 +746,9 @@ def _get_formatted_index(self, frame): formatter=fmt) else: fmt_index = [index.format(name=show_index_names, formatter=fmt)] + fmt_index = [tuple(_make_fixed_width( + list(x), justify='left', minimum=(self.col_space or 0))) + for x in fmt_index] adjoined = adjoin(1, *fmt_index).split('\n') diff --git a/pandas/tests/test_format.py b/pandas/tests/test_format.py index b52e4f7e3947b..f8598ef4d4294 100644 --- a/pandas/tests/test_format.py +++ b/pandas/tests/test_format.py @@ -298,6 +298,21 @@ def mkframe(n): com.pprint_thing(df._repr_fits_horizontal_()) self.assertTrue(has_expanded_repr(df)) + def test_str_max_colwidth(self): + # GH 7856 + df = pd.DataFrame([{'a': 'foo', 'b': 'bar', + 'c': 'uncomfortably long line with lots of stuff', + 'd': 1}, + {'a': 'foo', 'b': 'bar', 'c': 'stuff', 'd': 1}]) + df.set_index(['a', 'b', 'c']) + self.assertTrue(str(df) == ' a b c d\n' + '0 foo bar uncomfortably long line with lots of stuff 1\n' + '1 foo bar stuff 1') + with option_context('max_colwidth', 20): + self.assertTrue(str(df) == ' a b c d\n' + '0 foo bar uncomfortably lo... 1\n' + '1 foo bar stuff 1') + def test_auto_detect(self): term_width, term_height = get_terminal_size() fac = 1.05 # Arbitrary large factor to exceed term widht