Skip to content

Commit c348cbe

Browse files
Backport PR #38759: BUG: float-like string, trailing 0 truncation (#38769)
Co-authored-by: mzeitlin11 <[email protected]>
1 parent 79b8074 commit c348cbe

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

doc/source/whatsnew/v1.2.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- The deprecated attributes ``_AXIS_NAMES`` and ``_AXIS_NUMBERS`` of :class:`DataFrame` and :class:`Series` will no longer show up in ``dir`` or ``inspect.getmembers`` calls (:issue:`38740`)
1818
- :meth:`to_csv` created corrupted zip files when there were more rows than ``chunksize`` (issue:`38714`)
19+
- Bug in repr of float-like strings of an ``object`` dtype having trailing 0's truncated after the decimal (:issue:`38708`)
1920
-
2021

2122
.. ---------------------------------------------------------------------------

pandas/io/formats/format.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -1305,7 +1305,7 @@ def _format(x):
13051305
if not is_float_type[i] and leading_space:
13061306
fmt_values.append(f" {_format(v)}")
13071307
elif is_float_type[i]:
1308-
fmt_values.append(float_format(v))
1308+
fmt_values.append(_trim_zeros_single_float(float_format(v)))
13091309
else:
13101310
if leading_space is False:
13111311
# False specifically, so that the default is
@@ -1315,8 +1315,6 @@ def _format(x):
13151315
tpl = " {v}"
13161316
fmt_values.append(tpl.format(v=_format(v)))
13171317

1318-
fmt_values = _trim_zeros_float(str_floats=fmt_values, decimal=".")
1319-
13201318
return fmt_values
13211319

13221320

@@ -1832,11 +1830,25 @@ def _trim_zeros_complex(str_complexes: np.ndarray, decimal: str = ".") -> List[s
18321830
return padded
18331831

18341832

1833+
def _trim_zeros_single_float(str_float: str) -> str:
1834+
"""
1835+
Trims trailing zeros after a decimal point,
1836+
leaving just one if necessary.
1837+
"""
1838+
str_float = str_float.rstrip("0")
1839+
if str_float.endswith("."):
1840+
str_float += "0"
1841+
1842+
return str_float
1843+
1844+
18351845
def _trim_zeros_float(
18361846
str_floats: Union[np.ndarray, List[str]], decimal: str = "."
18371847
) -> List[str]:
18381848
"""
1839-
Trims zeros, leaving just one before the decimal points if need be.
1849+
Trims the maximum number of trailing zeros equally from
1850+
all numbers containing decimals, leaving just one if
1851+
necessary.
18401852
"""
18411853
trimmed = str_floats
18421854
number_regex = re.compile(fr"^\s*[\+-]?[0-9]+\{decimal}[0-9]*$")

pandas/tests/io/formats/test_format.py

+19
Original file line numberDiff line numberDiff line change
@@ -2002,6 +2002,25 @@ def test_float_trim_zeros(self):
20022002
assert ("+10" in line) or skip
20032003
skip = False
20042004

2005+
@pytest.mark.parametrize(
2006+
"data, expected",
2007+
[
2008+
(["3.50"], "0 3.50\ndtype: object"),
2009+
([1.20, "1.00"], "0 1.2\n1 1.00\ndtype: object"),
2010+
([np.nan], "0 NaN\ndtype: float64"),
2011+
([None], "0 None\ndtype: object"),
2012+
(["3.50", np.nan], "0 3.50\n1 NaN\ndtype: object"),
2013+
([3.50, np.nan], "0 3.5\n1 NaN\ndtype: float64"),
2014+
([3.50, np.nan, "3.50"], "0 3.5\n1 NaN\n2 3.50\ndtype: object"),
2015+
([3.50, None, "3.50"], "0 3.5\n1 None\n2 3.50\ndtype: object"),
2016+
],
2017+
)
2018+
def test_repr_str_float_truncation(self, data, expected):
2019+
# GH#38708
2020+
series = Series(data)
2021+
result = repr(series)
2022+
assert result == expected
2023+
20052024
def test_dict_entries(self):
20062025
df = DataFrame({"A": [{"a": 1, "b": 2}]})
20072026

0 commit comments

Comments
 (0)