Skip to content

Backport PR #38759 on branch 1.2.x (BUG: float-like string, trailing 0 truncation) #38769

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
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/v1.2.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Fixed regressions
~~~~~~~~~~~~~~~~~
- 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`)
- :meth:`to_csv` created corrupted zip files when there were more rows than ``chunksize`` (issue:`38714`)
- Bug in repr of float-like strings of an ``object`` dtype having trailing 0's truncated after the decimal (:issue:`38708`)
-

.. ---------------------------------------------------------------------------
Expand Down
20 changes: 16 additions & 4 deletions pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1305,7 +1305,7 @@ def _format(x):
if not is_float_type[i] and leading_space:
fmt_values.append(f" {_format(v)}")
elif is_float_type[i]:
fmt_values.append(float_format(v))
fmt_values.append(_trim_zeros_single_float(float_format(v)))
else:
if leading_space is False:
# False specifically, so that the default is
Expand All @@ -1315,8 +1315,6 @@ def _format(x):
tpl = " {v}"
fmt_values.append(tpl.format(v=_format(v)))

fmt_values = _trim_zeros_float(str_floats=fmt_values, decimal=".")

return fmt_values


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


def _trim_zeros_single_float(str_float: str) -> str:
"""
Trims trailing zeros after a decimal point,
leaving just one if necessary.
"""
str_float = str_float.rstrip("0")
if str_float.endswith("."):
str_float += "0"

return str_float


def _trim_zeros_float(
str_floats: Union[np.ndarray, List[str]], decimal: str = "."
) -> List[str]:
"""
Trims zeros, leaving just one before the decimal points if need be.
Trims the maximum number of trailing zeros equally from
all numbers containing decimals, leaving just one if
necessary.
"""
trimmed = str_floats
number_regex = re.compile(fr"^\s*[\+-]?[0-9]+\{decimal}[0-9]*$")
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/io/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2002,6 +2002,25 @@ def test_float_trim_zeros(self):
assert ("+10" in line) or skip
skip = False

@pytest.mark.parametrize(
"data, expected",
[
(["3.50"], "0 3.50\ndtype: object"),
([1.20, "1.00"], "0 1.2\n1 1.00\ndtype: object"),
([np.nan], "0 NaN\ndtype: float64"),
([None], "0 None\ndtype: object"),
(["3.50", np.nan], "0 3.50\n1 NaN\ndtype: object"),
([3.50, np.nan], "0 3.5\n1 NaN\ndtype: float64"),
([3.50, np.nan, "3.50"], "0 3.5\n1 NaN\n2 3.50\ndtype: object"),
([3.50, None, "3.50"], "0 3.5\n1 None\n2 3.50\ndtype: object"),
],
)
def test_repr_str_float_truncation(self, data, expected):
# GH#38708
series = Series(data)
result = repr(series)
assert result == expected

def test_dict_entries(self):
df = DataFrame({"A": [{"a": 1, "b": 2}]})

Expand Down