Skip to content

Commit a88003d

Browse files
yuanx749mroeschke
authored andcommitted
Backport PR pandas-dev#53855: BUG: Fix string formatting
1 parent 000a42f commit a88003d

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

doc/source/whatsnew/v2.0.3.rst

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ including other versions of pandas.
1414
Fixed regressions
1515
~~~~~~~~~~~~~~~~~
1616
- Fixed performance regression in merging on datetime-like columns (:issue:`53231`)
17+
- Fixed regression when :meth:`DataFrame.to_string` creates extra space for string dtypes (:issue:`52690`)
18+
- For external ExtensionArray implementations, restored the default use of ``_values_for_factorize`` for hashing arrays (:issue:`53475`)
1719
-
1820

1921
.. ---------------------------------------------------------------------------

pandas/io/formats/format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1426,7 +1426,7 @@ def _format(x):
14261426

14271427
fmt_values = []
14281428
for i, v in enumerate(vals):
1429-
if not is_float_type[i] and leading_space or self.formatter is not None:
1429+
if (not is_float_type[i] or self.formatter is not None) and leading_space:
14301430
fmt_values.append(f" {_format(v)}")
14311431
elif is_float_type[i]:
14321432
fmt_values.append(float_format(v))

pandas/tests/io/formats/test_format.py

+11
Original file line numberDiff line numberDiff line change
@@ -2165,6 +2165,17 @@ def test_max_rows_fitted(self, length, min_rows, max_rows, expected):
21652165
result = formatter.max_rows_fitted
21662166
assert result == expected
21672167

2168+
def test_no_extra_space(self):
2169+
# GH 52690: Check that no extra space is given
2170+
col1 = "TEST"
2171+
col2 = "PANDAS"
2172+
col3 = "to_string"
2173+
expected = f"{col1:<6s} {col2:<7s} {col3:<10s}"
2174+
df = DataFrame([{"col1": "TEST", "col2": "PANDAS", "col3": "to_string"}])
2175+
d = {"col1": "{:<6s}".format, "col2": "{:<7s}".format, "col3": "{:<10s}".format}
2176+
result = df.to_string(index=False, header=False, formatters=d)
2177+
assert result == expected
2178+
21682179

21692180
def gen_series_formatting():
21702181
s1 = Series(["a"] * 100)

0 commit comments

Comments
 (0)