Skip to content

Commit d7a387b

Browse files
authored
"Backport PR #35838 on branch 1.1.x" (#35915)
1 parent f86b129 commit d7a387b

File tree

4 files changed

+26
-4
lines changed

4 files changed

+26
-4
lines changed

doc/source/whatsnew/v1.1.2.rst

+2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ Fixed regressions
2424

2525
Bug fixes
2626
~~~~~~~~~
27+
28+
- Bug in :class:`Series` constructor raising a ``TypeError`` when constructing sparse datetime64 dtypes (:issue:`35762`)
2729
- Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`)
2830
- Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should bw ``""`` (:issue:`35712`)
2931
-

pandas/core/construction.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
is_iterator,
3636
is_list_like,
3737
is_object_dtype,
38+
is_sparse,
3839
is_timedelta64_ns_dtype,
3940
)
4041
from pandas.core.dtypes.generic import (
@@ -535,9 +536,10 @@ def _try_cast(
535536
if maybe_castable(arr) and not copy and dtype is None:
536537
return arr
537538

538-
if isinstance(dtype, ExtensionDtype) and dtype.kind != "M":
539+
if isinstance(dtype, ExtensionDtype) and (dtype.kind != "M" or is_sparse(dtype)):
539540
# create an extension array from its dtype
540-
# DatetimeTZ case needs to go through maybe_cast_to_datetime
541+
# DatetimeTZ case needs to go through maybe_cast_to_datetime but
542+
# SparseDtype does not
541543
array_type = dtype.construct_array_type()._from_sequence
542544
subarr = array_type(arr, dtype=dtype, copy=copy)
543545
return subarr

pandas/core/dtypes/cast.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
is_numeric_dtype,
5151
is_object_dtype,
5252
is_scalar,
53+
is_sparse,
5354
is_string_dtype,
5455
is_timedelta64_dtype,
5556
is_timedelta64_ns_dtype,
@@ -1323,7 +1324,9 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"):
13231324
f"Please pass in '{dtype.name}[ns]' instead."
13241325
)
13251326

1326-
if is_datetime64 and not is_dtype_equal(dtype, DT64NS_DTYPE):
1327+
if is_datetime64 and not is_dtype_equal(
1328+
getattr(dtype, "subtype", dtype), DT64NS_DTYPE
1329+
):
13271330

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

13611364
# have a scalar array-like (e.g. NaT)

pandas/tests/series/test_constructors.py

+15
Original file line numberDiff line numberDiff line change
@@ -1449,3 +1449,18 @@ def test_constructor_datetimelike_scalar_to_string_dtype(self):
14491449
result = Series("M", index=[1, 2, 3], dtype="string")
14501450
expected = pd.Series(["M", "M", "M"], index=[1, 2, 3], dtype="string")
14511451
tm.assert_series_equal(result, expected)
1452+
1453+
@pytest.mark.parametrize(
1454+
"values",
1455+
[
1456+
[np.datetime64("2012-01-01"), np.datetime64("2013-01-01")],
1457+
["2012-01-01", "2013-01-01"],
1458+
],
1459+
)
1460+
def test_constructor_sparse_datetime64(self, values):
1461+
# https://github.com/pandas-dev/pandas/issues/35762
1462+
dtype = pd.SparseDtype("datetime64[ns]")
1463+
result = pd.Series(values, dtype=dtype)
1464+
arr = pd.arrays.SparseArray(values, dtype=dtype)
1465+
expected = pd.Series(arr)
1466+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)