Skip to content

Commit 62fb061

Browse files
yuanx749reddyrg1mroeschke
authored
BUG: Fix string formatting (#53855)
* fixed string formatting bug * updating doc * add tests * change whatsnew * Update doc/source/whatsnew/v2.0.1.rst Co-authored-by: Matthew Roeschke <[email protected]> * Update v2.0.1.rst * Update v2.0.1.rst * change whatsnew * Update pandas/tests/io/formats/test_format.py Co-authored-by: Matthew Roeschke <[email protected]> * Fix bug with smaller change --------- Co-authored-by: Rithik Reddy <[email protected]> Co-authored-by: reddyrg1 <[email protected]> Co-authored-by: Matthew Roeschke <[email protected]>
1 parent 649b456 commit 62fb061

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

doc/source/whatsnew/v2.0.3.rst

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ 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`)
1718
- For external ExtensionArray implementations, restored the default use of ``_values_for_factorize`` for hashing arrays (:issue:`53475`)
1819
-
1920

pandas/io/formats/format.py

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

13921392
fmt_values = []
13931393
for i, v in enumerate(vals):
1394-
if not is_float_type[i] and leading_space or self.formatter is not None:
1394+
if (not is_float_type[i] or self.formatter is not None) and leading_space:
13951395
fmt_values.append(f" {_format(v)}")
13961396
elif is_float_type[i]:
13971397
fmt_values.append(float_format(v))

pandas/tests/io/formats/test_format.py

+11
Original file line numberDiff line numberDiff line change
@@ -2206,6 +2206,17 @@ def test_max_rows_fitted(self, length, min_rows, max_rows, expected):
22062206
result = formatter.max_rows_fitted
22072207
assert result == expected
22082208

2209+
def test_no_extra_space(self):
2210+
# GH 52690: Check that no extra space is given
2211+
col1 = "TEST"
2212+
col2 = "PANDAS"
2213+
col3 = "to_string"
2214+
expected = f"{col1:<6s} {col2:<7s} {col3:<10s}"
2215+
df = DataFrame([{"col1": "TEST", "col2": "PANDAS", "col3": "to_string"}])
2216+
d = {"col1": "{:<6s}".format, "col2": "{:<7s}".format, "col3": "{:<10s}".format}
2217+
result = df.to_string(index=False, header=False, formatters=d)
2218+
assert result == expected
2219+
22092220

22102221
def gen_series_formatting():
22112222
s1 = Series(["a"] * 100)

0 commit comments

Comments
 (0)