Skip to content

Fixed to_string with line_width and without index #13998

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 15, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.19.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -989,3 +989,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.
7 changes: 5 additions & 2 deletions pandas/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down