diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 98941b6d353bb..b614d760c7b7d 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -1303,6 +1303,7 @@ Indexing - Bug where setting a timedelta column by ``Index`` causes it to be casted to double, and therefore lose precision (:issue:`23511`) - Bug in :func:`Index.union` and :func:`Index.intersection` where name of the ``Index`` of the result was not computed correctly for certain cases (:issue:`9943`, :issue:`9862`) - Bug in :class:`Index` slicing with boolean :class:`Index` may raise ``TypeError`` (:issue:`22533`) +- Bug when :class:`Series` was created from :class:`DatetimeIndex`, the series shares the same data with that index (:issue:`21907`) Missing ^^^^^^^ diff --git a/pandas/core/series.py b/pandas/core/series.py index 892b24f6ee552..9ecb4b52bbb46 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -181,8 +181,11 @@ def __init__(self, data=None, index=None, dtype=None, name=None, # astype copies data = data.astype(dtype) else: - # need to copy to avoid aliasing issues - data = data._values.copy() + # GH21907 + if isinstance(data._values, DatetimeIndex): + data = data.copy(deep=True) + else: + data = data._values.copy() copy = False elif isinstance(data, np.ndarray): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index ce0cf0d5c089e..8106fa8125103 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -970,6 +970,24 @@ def test_constructor_set(self): values = frozenset(values) pytest.raises(TypeError, Series, values) + @pytest.mark.parametrize( + "src", + [pd.date_range('2016-01-01', periods=10, tz='US/Pacific'), + pd.timedelta_range('1 day', periods=10), + pd.period_range('2012Q1', periods=3, freq='Q'), + pd.Index(list('abcdefghij')), + pd.Int64Index(np.arange(10)), + pd.RangeIndex(0, 10)]) + def test_fromIndex(self, src): + # GH21907 + # When constructing a series from an index, + # the series does not share data with that index + expected = src.copy(deep=True) + prod = Series(src) + prod[::3] = NaT + assert expected[0] is not NaT + tm.assert_index_equal(src, expected) + # https://github.com/pandas-dev/pandas/issues/22698 @pytest.mark.filterwarnings("ignore:elementwise comparison:FutureWarning") def test_fromDict(self):