From 2bd86299ae11e069eab702d5b2775dc71b1b072c Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Tue, 27 Dec 2016 15:41:00 -0600 Subject: [PATCH] BUG: Fixed to_html with index=False and max_rows closes https://github.com/pandas-dev/pandas/issues/14998 Previously raised an IndexError by assuming that `len(fmt_values)` was always the same length as `len(self.data)`. --- doc/source/whatsnew/v0.20.0.txt | 6 ++++++ pandas/formats/format.py | 2 +- pandas/tests/formats/test_format.py | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index 0873e4b34b0b1..5e27c6e9cc293 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -313,6 +313,12 @@ Bug Fixes +- Bug in ``DataFrame.to_html`` with ``index=False`` and ``max_rows`` raising in ``IndexError`` (:issue:`14998`) + + + + + diff --git a/pandas/formats/format.py b/pandas/formats/format.py index 0cf6050e515e0..a3319437474c2 100644 --- a/pandas/formats/format.py +++ b/pandas/formats/format.py @@ -1182,7 +1182,7 @@ def _write_body(self, indent): else: self._write_regular_rows(fmt_values, indent) else: - for i in range(len(self.frame)): + for i in range(min(len(self.frame), self.max_rows)): row = [fmt_values[j][i] for j in range(len(self.columns))] self.write_tr(row, indent, self.indent_delta, tags=None) diff --git a/pandas/tests/formats/test_format.py b/pandas/tests/formats/test_format.py index e7c32a4baa4ea..00e5e002ca48d 100644 --- a/pandas/tests/formats/test_format.py +++ b/pandas/tests/formats/test_format.py @@ -2771,6 +2771,25 @@ def test_to_html_with_classes(self): result = df.to_html(classes=["sortable", "draggable"]) self.assertEqual(result, expected) + def test_to_html_no_index_max_rows(self): + # GH https://github.com/pandas-dev/pandas/issues/14998 + df = DataFrame({"A": [1, 2, 3, 4]}) + result = df.to_html(index=False, max_rows=1) + expected = dedent("""\ + + + + + + + + + + + +
A
1
""") + self.assertEqual(result, expected) + def test_pprint_pathological_object(self): """ if the test fails, the stack will overflow and nose crash,