diff --git a/doc/source/whatsnew/v0.19.0.txt b/doc/source/whatsnew/v0.19.0.txt index c58af7ad4e327..d436d4dd3703b 100644 --- a/doc/source/whatsnew/v0.19.0.txt +++ b/doc/source/whatsnew/v0.19.0.txt @@ -990,3 +990,4 @@ Bug Fixes - Bug in ``Index`` raises ``KeyError`` displaying incorrect column when column is not in the df and columns contains duplicate values (:issue:`13822`) - Bug in ``Period`` and ``PeriodIndex`` creating wrong dates when frequency has combined offset aliases (:issue:`13874`) - Bug in ``pd.to_datetime()`` did not cast floats correctly when ``unit`` was specified, resulting in truncated datetime (:issue:`13845`) +- Bug in ``.to_string()`` when called with an integer ``line_width`` and ``index=False`` raises an UnboundLocalError exception because ``idx`` referenced before assignment. diff --git a/pandas/formats/format.py b/pandas/formats/format.py index 50d54ddb95100..f89ceaff2ad64 100644 --- a/pandas/formats/format.py +++ b/pandas/formats/format.py @@ -68,7 +68,9 @@ Set to False for a DataFrame with a hierarchical index to print every multiindex key at each row, default True index_names : bool, optional - Prints the names of the indexes, default True""" + Prints the names of the indexes, default True + line_width : int, optional + Width to wrap a line in characters, default no wrap""" justify_docstring = """ justify : {'left', 'right'}, default None @@ -632,7 +634,8 @@ def _join_multiline(self, *strcols): st = 0 for i, ed in enumerate(col_bins): row = strcols[st:ed] - row.insert(0, idx) + if self.index: + row.insert(0, idx) if nbins > 1: if ed <= len(strcols) and i < nbins - 1: row.append([' \\'] + [' '] * (nrows - 1)) diff --git a/pandas/tests/formats/test_format.py b/pandas/tests/formats/test_format.py index 1580a33fb9456..8a4aca2b320aa 100644 --- a/pandas/tests/formats/test_format.py +++ b/pandas/tests/formats/test_format.py @@ -1964,6 +1964,14 @@ def test_to_string_no_index(self): self.assertEqual(df_s, expected) + def test_to_string_line_width_no_index(self): + df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]}) + + df_s = df.to_string(line_width=1, index=False) + expected = "x \\\n1 \n2 \n3 \n\ny \n4 \n5 \n6" + + self.assertEqual(df_s, expected) + def test_to_string_float_formatting(self): self.reset_display_options() fmt.set_option('display.precision', 5, 'display.column_space', 12,