Skip to content

Fix Series construction from Sparse["datetime64[ns]"] #35838

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 4 commits into from
Aug 27, 2020
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.1.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
- Bug in :meth:`DataFrame.eval` with ``object`` dtype column binary operations (:issue:`35794`)
- Bug in :class:`Series` constructor raising a ``TypeError`` when constructing sparse datetime64 dtypes (:issue:`35762`)
- Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`)
-
-
Expand Down
6 changes: 4 additions & 2 deletions pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
is_iterator,
is_list_like,
is_object_dtype,
is_sparse,
is_timedelta64_ns_dtype,
)
from pandas.core.dtypes.generic import (
Expand Down Expand Up @@ -535,9 +536,10 @@ def _try_cast(
if maybe_castable(arr) and not copy and dtype is None:
return arr

if isinstance(dtype, ExtensionDtype) and dtype.kind != "M":
if isinstance(dtype, ExtensionDtype) and (dtype.kind != "M" or is_sparse(dtype)):
# create an extension array from its dtype
# DatetimeTZ case needs to go through maybe_cast_to_datetime
# DatetimeTZ case needs to go through maybe_cast_to_datetime but
# SparseDtype does not
array_type = dtype.construct_array_type()._from_sequence
subarr = array_type(arr, dtype=dtype, copy=copy)
return subarr
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
is_numeric_dtype,
is_object_dtype,
is_scalar,
is_sparse,
is_string_dtype,
is_timedelta64_dtype,
is_timedelta64_ns_dtype,
Expand Down Expand Up @@ -1323,7 +1324,9 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"):
f"Please pass in '{dtype.name}[ns]' instead."
)

if is_datetime64 and not is_dtype_equal(dtype, DT64NS_DTYPE):
if is_datetime64 and not is_dtype_equal(
getattr(dtype, "subtype", dtype), DT64NS_DTYPE
):

# pandas supports dtype whose granularity is less than [ns]
# e.g., [ps], [fs], [as]
Expand Down Expand Up @@ -1355,7 +1358,7 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"):
if is_scalar(value):
if value == iNaT or isna(value):
value = iNaT
else:
elif not is_sparse(value):
value = np.array(value, copy=False)

# have a scalar array-like (e.g. NaT)
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1449,3 +1449,18 @@ def test_constructor_datetimelike_scalar_to_string_dtype(self):
result = Series("M", index=[1, 2, 3], dtype="string")
expected = pd.Series(["M", "M", "M"], index=[1, 2, 3], dtype="string")
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"values",
[
[np.datetime64("2012-01-01"), np.datetime64("2013-01-01")],
["2012-01-01", "2013-01-01"],
],
)
def test_constructor_sparse_datetime64(self, values):
# https://github.com/pandas-dev/pandas/issues/35762
dtype = pd.SparseDtype("datetime64[ns]")
result = pd.Series(values, dtype=dtype)
arr = pd.arrays.SparseArray(values, dtype=dtype)
expected = pd.Series(arr)
tm.assert_series_equal(result, expected)