Skip to content

Commit ef61beb

Browse files
cr3jorisvandenbossche
authored andcommitted
Fixed to_string with line_width and without index (pandas-dev#13998)
1 parent 66f9591 commit ef61beb

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v0.19.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -990,3 +990,4 @@ Bug Fixes
990990
- Bug in ``Index`` raises ``KeyError`` displaying incorrect column when column is not in the df and columns contains duplicate values (:issue:`13822`)
991991
- Bug in ``Period`` and ``PeriodIndex`` creating wrong dates when frequency has combined offset aliases (:issue:`13874`)
992992
- Bug in ``pd.to_datetime()`` did not cast floats correctly when ``unit`` was specified, resulting in truncated datetime (:issue:`13845`)
993+
- Bug in ``.to_string()`` when called with an integer ``line_width`` and ``index=False`` raises an UnboundLocalError exception because ``idx`` referenced before assignment.

pandas/formats/format.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@
6868
Set to False for a DataFrame with a hierarchical index to print every
6969
multiindex key at each row, default True
7070
index_names : bool, optional
71-
Prints the names of the indexes, default True"""
71+
Prints the names of the indexes, default True
72+
line_width : int, optional
73+
Width to wrap a line in characters, default no wrap"""
7274

7375
justify_docstring = """
7476
justify : {'left', 'right'}, default None
@@ -632,7 +634,8 @@ def _join_multiline(self, *strcols):
632634
st = 0
633635
for i, ed in enumerate(col_bins):
634636
row = strcols[st:ed]
635-
row.insert(0, idx)
637+
if self.index:
638+
row.insert(0, idx)
636639
if nbins > 1:
637640
if ed <= len(strcols) and i < nbins - 1:
638641
row.append([' \\'] + [' '] * (nrows - 1))

pandas/tests/formats/test_format.py

+8
Original file line numberDiff line numberDiff line change
@@ -1964,6 +1964,14 @@ def test_to_string_no_index(self):
19641964

19651965
self.assertEqual(df_s, expected)
19661966

1967+
def test_to_string_line_width_no_index(self):
1968+
df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
1969+
1970+
df_s = df.to_string(line_width=1, index=False)
1971+
expected = "x \\\n1 \n2 \n3 \n\ny \n4 \n5 \n6"
1972+
1973+
self.assertEqual(df_s, expected)
1974+
19671975
def test_to_string_float_formatting(self):
19681976
self.reset_display_options()
19691977
fmt.set_option('display.precision', 5, 'display.column_space', 12,

0 commit comments

Comments
 (0)