Skip to content

BUG: Series(dt64, dtype="Sparse[object]") #38508

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

Closed
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
16 changes: 9 additions & 7 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
conversion,
iNaT,
ints_to_pydatetime,
ints_to_pytimedelta,
)
from pandas._libs.tslibs.timezones import tz_compare
from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar
Expand Down Expand Up @@ -987,15 +986,20 @@ def astype_nansafe(
elif not isinstance(dtype, np.dtype):
raise ValueError("dtype must be np.dtype or ExtensionDtype")

if arr.dtype.kind in ["m", "M"] and dtype == object:
# make sure we wrap in Timedelta/Timestamp, not timedelta/datetime
from pandas.core.construction import ensure_wrapped_if_datetimelike

arr = ensure_wrapped_if_datetimelike(arr)
return arr.astype(dtype, copy=copy)

if issubclass(dtype.type, str):
return lib.ensure_string_array(
arr.ravel(), skipna=skipna, convert_na_value=False
).reshape(arr.shape)

elif is_datetime64_dtype(arr):
if is_object_dtype(dtype):
return ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
if dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
return arr.view(dtype)
Expand All @@ -1007,9 +1011,7 @@ def astype_nansafe(
raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]")

elif is_timedelta64_dtype(arr):
if is_object_dtype(dtype):
return ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
if dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
return arr.view(dtype)
Expand Down
10 changes: 0 additions & 10 deletions pandas/core/internals/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,16 +677,6 @@ def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike:
# StringDtype, this matches arr.astype(dtype), xref GH#36153
values = arr._format_native_types(na_rep="NaT")

elif is_object_dtype(dtype):
if values.dtype.kind in ["m", "M"]:
# Wrap in Timedelta/Timestamp
arr = pd_array(values)
values = arr.astype(object)
else:
values = values.astype(object)
# We still need to go through astype_nansafe for
# e.g. dtype = Sparse[object, 0]

values = astype_nansafe(values, dtype, copy=True)

return values
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/dtypes/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -754,6 +754,19 @@ def test_astype_object_preserves_datetime_na(from_type):
assert isna(result)[0]


@pytest.mark.parametrize("from_dtype", ["datetime64[ns]", "timedelta64[ns]"])
def test_astype_object_boxes_timestamps_timedeltas(from_dtype):
arr = np.array([3600], dtype=from_dtype)
result = astype_nansafe(arr, dtype=np.dtype("object"))

assert result.dtype == object

if from_dtype == "datetime64[ns]":
assert isinstance(result[0], pd.Timestamp)
else:
assert isinstance(result[0], pd.Timedelta)


def test_validate_allhashable():
assert com.validate_all_hashable(1, "a") is None

Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
Period,
RangeIndex,
Series,
Timedelta,
Timestamp,
date_range,
isna,
Expand Down Expand Up @@ -1513,6 +1514,22 @@ def test_constructor_sparse_datetime64(self, values):
expected = Series(arr)
tm.assert_series_equal(result, expected)

def test_constructor_datetimelike_to_sparse_object(self):
arr = np.arange(3, dtype="i8").view("M8[D]").astype("M8[ns]")
arr2 = arr.view("m8[ns]")

ser = Series(arr, dtype="Sparse[object]")
assert isinstance(ser[0], Timestamp)
Copy link
Contributor

Choose a reason for hiding this comment

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

why wouldn't these be Sparse[datetime64[ns]] ? (and equiv for timedelta). do we actually have a usecase for embedding non-object dtypes here? I think this something that we should limit (as we do coercion on non-sparse things if they are datetimelike already this is a big change).

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure i understand the question. are you asking why L1521 isnt ser = Series(arr, dtype="Sparse[datetime64[ns]]")?

Looking at the non-sparse, case Series(arr, dtype=object)[0] returns a pydatetime object, so i guess its OK that Sparse[object] does the same.

Really the motivation is to make astype_nansafe with dt64 data behave the same as DatetimeArray.astype and Block._astype so we can share more.


ser = Series(arr).astype("Sparse[object]")
assert isinstance(ser[0], Timestamp)

ser2 = Series(arr2, dtype="Sparse[object]")
assert isinstance(ser2[0], Timedelta)

ser2 = Series(arr2).astype("Sparse[object]")
assert isinstance(ser2[0], Timedelta)

def test_construction_from_ordered_collection(self):
# https://github.com/pandas-dev/pandas/issues/36044
result = Series({"a": 1, "b": 2}.keys())
Expand Down