Skip to content

ENH: Add equivalence test for float in to_numeric() GH43693 #43710

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 1 commit into from
Jan 17, 2022
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.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ enhancement2
Other enhancements
^^^^^^^^^^^^^^^^^^
- Improved the rendering of ``categories`` in :class:`CategoricalIndex` (:issue:`45218`)
- :meth:`to_numeric` now preserves float64 arrays when downcasting would generate values not representable in float32 (:issue:`43693`)
-

.. ---------------------------------------------------------------------------
Expand Down
12 changes: 11 additions & 1 deletion pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,17 @@ def trans(x):
and not is_bool_dtype(result.dtype)
and not is_string_dtype(result.dtype)
):
return result.astype(dtype)
new_result = result.astype(dtype)

# Adjust tolerances based on floating point size
size_tols = {4: 5e-4, 8: 5e-8, 16: 5e-16}

atol = size_tols.get(new_result.dtype.itemsize, 0.0)

# Check downcast float values are still equal within 7 digits when
# converting from float64 to float32
if np.allclose(new_result, result, equal_nan=True, rtol=0.0, atol=atol):
return new_result

return result

Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/tools/test_to_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,14 @@ def test_downcast_limits(dtype, downcast, min_max):
assert series.dtype == dtype


def test_downcast_float64_to_float32():
# GH-43693: Check float64 preservation when >= 16,777,217
series = Series([16777217.0, np.finfo(np.float64).max, np.nan], dtype=np.float64)
result = to_numeric(series, downcast="float")

assert series.dtype == result.dtype


@pytest.mark.parametrize(
"ser,expected",
[
Expand Down Expand Up @@ -762,6 +770,8 @@ def test_to_numeric_from_nullable_string(values, nullable_string_dtype, expected
([-1, -1], "Int32", "unsigned", "Int32"),
([1, 1], "Float64", "float", "Float32"),
([1, 1.1], "Float64", "float", "Float32"),
([1, 1], "Float32", "float", "Float32"),
([1, 1.1], "Float32", "float", "Float32"),
),
)
def test_downcast_nullable_numeric(data, input_dtype, downcast, expected_dtype):
Expand Down