Skip to content

BUG: Fix justification for DataFrame.to_string(index=False) #14569

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

Closed
wants to merge 4 commits into from
Closed
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
11 changes: 9 additions & 2 deletions pandas/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,8 +604,15 @@ def to_string(self):
self._chk_truncate()
strcols = self._to_str_columns()
text = self.adj.adjoin(1, *strcols)
if not self.index:
text = text.replace('\n ', '\n').strip()

first_column_dtype = (None if len(frame.columns) == 0
else frame.dtypes[frame.columns[0]])
if not self.index and first_column_dtype.kind != 'O':
# Remove a single space from the beginning of each line
# and remove any trailing spaces
if len(text) > 0 and text[0] == ' ':
text = text[1:]
text = text.replace('\n ', '\n').rstrip()
self.buf.writelines(text)

if self.should_show_dimensions:
Expand Down
39 changes: 37 additions & 2 deletions pandas/tests/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1974,11 +1974,46 @@ def test_to_string_no_header(self):
self.assertEqual(df_s, expected)

def test_to_string_no_index(self):
df = DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
df = DataFrame({'aaaaa': [100, 200, 300], 'bbbbb': [400, 500, 600]})
df_s = df.to_string(index=False)
expected = "aaaaa bbbbb\n" \
" 100 400\n" \
" 200 500\n" \
" 300 600"
self.assertEqual(df_s, expected)

df = DataFrame({'aaa': [100, 200, 300], 'bbb': [400, 500, 600]})
df_s = df.to_string(index=False)
expected = "x y\n1 4\n2 5\n3 6"
expected = "aaa bbb\n" \
"100 400\n" \
"200 500\n" \
"300 600"
self.assertEqual(df_s, expected)

df = DataFrame({'a': [100, 200, 300], 'b': [400, 500, 600]})
df_s = df.to_string(index=False)
expected = " a b\n" \
"100 400\n" \
"200 500\n" \
"300 600"
self.assertEqual(df_s, expected)

df = DataFrame({'aaaaa': ['xxx', 'xxx', 'xxx'],
'bbbbb': ['xxx', 'xxx', 'xxx']})
df_s = df.to_string(index=False)
expected = "aaaaa bbbbb\n" \
" xxx xxx\n" \
" xxx xxx\n" \
" xxx xxx"
self.assertEqual(df_s, expected)

df = DataFrame({'aaaaa': [-1.0, -2.0, -3.0],
'bbbbb': [-4.0, -5.0, -6.0]})
df_s = df.to_string(index=False)
expected = "aaaaa bbbbb\n" \
" -1.0 -4.0\n" \
" -2.0 -5.0\n" \
" -3.0 -6.0"
self.assertEqual(df_s, expected)

def test_to_string_line_width_no_index(self):
Expand Down