Skip to content

BUG: SparseArray.astype(np.int64) #49704

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 3 commits into from
Nov 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -722,7 +722,7 @@ Reshaping

Sparse
^^^^^^
-
- Bug in :meth:`Series.astype` when converting a ``SparseDtype`` with ``datetime64[ns]`` subtype to ``int64`` dtype raising, inconsistent with the non-sparse behavior (:issue:`49631`)
-

ExtensionArray
Expand Down
26 changes: 10 additions & 16 deletions pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@
validate_insert_loc,
)

from pandas.core.dtypes.astype import astype_nansafe
from pandas.core.dtypes.astype import (
astype_array,
astype_nansafe,
)
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
find_common_type,
Expand Down Expand Up @@ -90,6 +93,7 @@
from pandas.core.base import PandasObject
import pandas.core.common as com
from pandas.core.construction import (
ensure_wrapped_if_datetimelike,
extract_array,
sanitize_array,
)
Expand Down Expand Up @@ -120,8 +124,6 @@ class ellipsis(Enum):

SparseIndexKind = Literal["integer", "block"]

from pandas.core.dtypes.dtypes import ExtensionDtype

from pandas import Series

else:
Expand Down Expand Up @@ -1305,24 +1307,16 @@ def astype(self, dtype: AstypeArg | None = None, copy: bool = True):
future_dtype = pandas_dtype(dtype)
if not isinstance(future_dtype, SparseDtype):
# GH#34457
if isinstance(future_dtype, np.dtype):
values = np.array(self)
return astype_nansafe(values, dtype=future_dtype)
else:
# pylint: disable-next=used-before-assignment
dtype = cast(ExtensionDtype, dtype)
cls = dtype.construct_array_type()
return cls._from_sequence(self, dtype=dtype, copy=copy)
values = np.asarray(self)
Copy link
Member

Choose a reason for hiding this comment

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

Is this robust if the original type was pd.SparseDtype(pd.Int64Dtype) with an NA and astype(pd.Int32Dtype) was called?

Copy link
Member

Choose a reason for hiding this comment

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

Oh looks like there an existing bug here too (missing import)

In [1]: arr = pd.array([1, pd.NA], dtype=pd.SparseDtype(pd.Int64Dtype()))

In [2]: arr
Out[2]:
[1, <NA>]
Fill: <NA>
IntIndex
Indices: array([0], dtype=int32)

In [3]: arr.dtype
Out[3]: Sparse[Int64, <NA>]

In [4]: arr.astype(pd.Int16Dtype())
NameError: name 'ExtensionDtype' is not defined

Copy link
Member Author

@jbrockmendel jbrockmendel Nov 16, 2022

Choose a reason for hiding this comment

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

yah, though i think that was introduced by a pylint PR really recently. updatenope it was introduced by me 15 days ago

also IIUC pd.SparseDtype(EADtype) shouldn't work.

Copy link
Member

Choose a reason for hiding this comment

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

Could you raise a NotImplementedError for the EADtypes here for now then?

Copy link
Member Author

Choose a reason for hiding this comment

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

id rather do that as separately to Do It Right along with a couple other bugs mentioned in #49631

values = ensure_wrapped_if_datetimelike(values)
return astype_array(values, dtype=future_dtype, copy=False)

dtype = self.dtype.update_dtype(dtype)
subtype = pandas_dtype(dtype._subtype_with_str)
subtype = cast(np.dtype, subtype) # ensured by update_dtype
sp_values = astype_nansafe(self.sp_values, subtype, copy=copy)

# error: Argument 1 to "_simple_new" of "SparseArray" has incompatible type
# "ExtensionArray"; expected "ndarray"
return self._simple_new(
sp_values, self.sp_index, dtype # type: ignore[arg-type]
)
return self._simple_new(sp_values, self.sp_index, dtype)

def map(self: SparseArrayT, mapper) -> SparseArrayT:
"""
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/arrays/sparse/test_astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,12 @@ def test_astype_copy_false(self):
result = arr.astype(dtype, copy=False)
expected = SparseArray([1.0, 2.0, 3.0], fill_value=0.0)
tm.assert_sp_array_equal(result, expected)

def test_astype_dt64_to_int64(self):
# GH#49631 match non-sparse behavior
values = np.array(["NaT", "2016-01-02", "2016-01-03"], dtype="M8[ns]")

arr = SparseArray(values)
result = arr.astype("int64")
expected = values.astype("int64")
tm.assert_numpy_array_equal(result, expected)