Skip to content
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

Support downcasting of nullable arrays #33435

Closed
wants to merge 6 commits into from
Closed
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.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ Other enhancements
- :class:`Series.str` now has a `fullmatch` method that matches a regular expression against the entire string in each row of the series, similar to `re.fullmatch` (:issue:`32806`).
- :meth:`DataFrame.sample` will now also allow array-like and BitGenerator objects to be passed to ``random_state`` as seeds (:issue:`32503`)
- :meth:`MultiIndex.union` will now raise `RuntimeWarning` if the object inside are unsortable, pass `sort=False` to suppress this warning (:issue:`33015`)
- :func:`to_numeric` will now support downcasting of nullable dtypes.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add the issue number

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move to 1.2

-

.. ---------------------------------------------------------------------------
Expand Down
11 changes: 5 additions & 6 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ def maybe_downcast_to_dtype(result, dtype):

else:
dtype = "object"

dtype = np.dtype(dtype)

converted = maybe_downcast_numeric(result, dtype, do_round)
if converted is not result:
return converted
Expand Down Expand Up @@ -180,7 +178,8 @@ def maybe_downcast_to_dtype(result, dtype):

def maybe_downcast_numeric(result, dtype, do_round: bool = False):
"""
Subset of maybe_downcast_to_dtype restricted to numeric dtypes.
Subset of maybe_downcast_to_dtype restricted to numeric and
nullable dtypes.

Parameters
----------
Expand Down Expand Up @@ -210,9 +209,7 @@ def trans(x):
# don't allow upcasts here (except if empty)
if result.dtype.itemsize <= dtype.itemsize and result.size:
return result

if is_bool_dtype(dtype) or is_integer_dtype(dtype):

if not result.size:
# if we don't have any elements, just astype it
return trans(result).astype(dtype)
Expand All @@ -239,7 +236,9 @@ def trans(x):
if (new_result == result).all():
return new_result
else:
if np.allclose(new_result, result, rtol=0):
# np.allclose raises TypeError on extension arrays
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm not sure about this. I think allclose should still work and maybe that is the root cause instead, but let's see what others think

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i agree , we might need to enable soething on EAs to make this work, but that is the root cause

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you elaborate on enabling something on EAs? Would this be a new feature to it, or a current feature?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what happens when this is on an EA (e.g. show an exampel with this line specifically)

nd_result = np.array(result).astype(result[0].dtype)
if np.allclose(new_result, nd_result, rtol=0):
return new_result

elif (
Expand Down
1 change: 0 additions & 1 deletion pandas/core/tools/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,6 @@ def to_numeric(arg, errors="raise", downcast=None):
# to a numerical dtype and if a downcast method has been specified
if downcast is not None and is_numeric_dtype(values):
typecodes = None

if downcast in ("integer", "signed"):
typecodes = np.typecodes["Integer"]
elif downcast == "unsigned" and (not len(values) or np.min(values) >= 0):
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/tools/test_to_numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -649,3 +649,14 @@ def test_failure_to_convert_uint64_string_to_NaN():
ser = Series([32, 64, np.nan])
result = to_numeric(pd.Series(["32", "64", "uint64"]), errors="coerce")
tm.assert_series_equal(result, ser)


def test_support_downcast_of_nullable_dtypes():
# GH 33013
try:
pd.to_numeric(pd.Series([1, 2, 3], dtype="Int32"), downcast="integer")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you parametrize these instead?

pd.to_numeric(pd.Series([1, 2, 3], dtype="Int64"), downcast="integer")
pd.to_numeric(pd.Series([1, 2], dtype="Int32"), downcast="signed")
pd.to_numeric(pd.Series([1, 2, 3], dtype="Int32"), downcast="float")
except TypeError:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than the try...except you would ideally do expected = ... and do tm.assert_frame_equal(result, expected) for the various cases; you will see this throughout other tests if you need a place to look

pytest.fail("TypeError raised.")