Skip to content

Commit 3fae915

Browse files
Backport PR #40850: REGR: object column repr not respecting float format (#40875)
Co-authored-by: Matthew Zeitlin <[email protected]>
1 parent 8493555 commit 3fae915

File tree

5 files changed

+64
-3
lines changed

5 files changed

+64
-3
lines changed

doc/source/whatsnew/v1.2.4.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Fixed regressions
2020
- Fixed regression in (in)equality comparison of ``pd.NaT`` with a non-datetimelike numpy array returning a scalar instead of an array (:issue:`40722`)
2121
- Fixed regression in :meth:`DataFrame.where` not returning a copy in the case of an all True condition (:issue:`39595`)
2222
- Fixed regression in :meth:`DataFrame.replace` raising ``IndexError`` when ``regex`` was a multi-key dictionary (:issue:`39338`)
23-
-
23+
- Fixed regression in repr of floats in an ``object`` column not respecting ``float_format`` when printed in the console or outputted through :meth:`DataFrame.to_string`, :meth:`DataFrame.to_html`, and :meth:`DataFrame.to_latex` (:issue:`40024`)
2424

2525
.. ---------------------------------------------------------------------------
2626

pandas/io/formats/format.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1254,7 +1254,9 @@ def _format_strings(self) -> List[str]:
12541254
float_format = get_option("display.float_format")
12551255
if float_format is None:
12561256
precision = get_option("display.precision")
1257-
float_format = lambda x: f"{x: .{precision:d}f}"
1257+
float_format = lambda x: _trim_zeros_single_float(
1258+
f"{x: .{precision:d}f}"
1259+
)
12581260
else:
12591261
float_format = self.float_format
12601262

@@ -1305,7 +1307,7 @@ def _format(x):
13051307
if not is_float_type[i] and leading_space:
13061308
fmt_values.append(f" {_format(v)}")
13071309
elif is_float_type[i]:
1308-
fmt_values.append(_trim_zeros_single_float(float_format(v)))
1310+
fmt_values.append(float_format(v))
13091311
else:
13101312
if leading_space is False:
13111313
# False specifically, so that the default is

pandas/tests/io/formats/test_format.py

+15
Original file line numberDiff line numberDiff line change
@@ -2021,6 +2021,21 @@ def test_repr_str_float_truncation(self, data, expected):
20212021
result = repr(series)
20222022
assert result == expected
20232023

2024+
@pytest.mark.parametrize(
2025+
"float_format,expected",
2026+
[
2027+
("{:,.0f}".format, "0 1,000\n1 test\ndtype: object"),
2028+
("{:.4f}".format, "0 1000.0000\n1 test\ndtype: object"),
2029+
],
2030+
)
2031+
def test_repr_float_format_in_object_col(self, float_format, expected):
2032+
# GH#40024
2033+
df = Series([1000.0, "test"])
2034+
with option_context("display.float_format", float_format):
2035+
result = repr(df)
2036+
2037+
assert result == expected
2038+
20242039
def test_dict_entries(self):
20252040
df = DataFrame({"A": [{"a": 1, "b": 2}]})
20262041

pandas/tests/io/formats/test_to_html.py

+26
Original file line numberDiff line numberDiff line change
@@ -878,3 +878,29 @@ def test_to_html_na_rep_and_float_format(na_rep):
878878
</tbody>
879879
</table>"""
880880
assert result == expected
881+
882+
883+
def test_to_html_float_format_object_col():
884+
# GH#40024
885+
df = DataFrame(data={"x": [1000.0, "test"]})
886+
result = df.to_html(float_format=lambda x: f"{x:,.0f}")
887+
expected = """<table border="1" class="dataframe">
888+
<thead>
889+
<tr style="text-align: right;">
890+
<th></th>
891+
<th>x</th>
892+
</tr>
893+
</thead>
894+
<tbody>
895+
<tr>
896+
<th>0</th>
897+
<td>1,000</td>
898+
</tr>
899+
<tr>
900+
<th>1</th>
901+
<td>test</td>
902+
</tr>
903+
</tbody>
904+
</table>"""
905+
906+
assert result == expected

pandas/tests/io/formats/test_to_latex.py

+18
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,24 @@ def test_to_latex_column_format(self):
121121
)
122122
assert result == expected
123123

124+
def test_to_latex_float_format_object_col(self):
125+
# GH#40024
126+
ser = Series([1000.0, "test"])
127+
result = ser.to_latex(float_format="{:,.0f}".format)
128+
expected = _dedent(
129+
r"""
130+
\begin{tabular}{ll}
131+
\toprule
132+
{} & 0 \\
133+
\midrule
134+
0 & 1,000 \\
135+
1 & test \\
136+
\bottomrule
137+
\end{tabular}
138+
"""
139+
)
140+
assert result == expected
141+
124142
def test_to_latex_empty_tabular(self):
125143
df = DataFrame()
126144
result = df.to_latex()

0 commit comments

Comments
 (0)